0

The following attempts to send a file from an Angular2 app always end-up in the REST API not being able to recognize the file in the request. (Even if the content seams to be there !)

After spending hours searching StackOverflow and countless other online sources, i came to the conclusion that the most recent version of Angular2 Http module/service should now be capable of handling file uploads. (The fact that it wasn't able to do so in the past is just amazing !)

Component.html

    <form [formGroup]="profileForm" (ngSubmit)="onSubmit()" novalidate>
        <label>Votre avatar !</label>
        <input class="form-control" type="file" name="avatar" (change)="imageUpload($event)"  >
            

Component.ts

  imageUpload(e) {
    let reader = new FileReader();
    //get the selected file from event
    let file = e.target.files[0];
    reader.onloadend = () => {
      this.image = reader.result;
     }
    reader.readAsDataURL(file);
  }


  onSubmit() {
    if (this.image){
          this.authService.setAvatar(this.image).subscribe(
            d => {
              //Do Nothing... Will navigate to this.router.url anyway so...
            },
            err =>{
              this.errorMessage = err;
              console.log(err);
            }

          );
        }
  }

authService.ts

setAvatar(image:any){
    
    let form: FormData  = new FormData();
    form.append('avatar', image);
    return this.http.post (Config.REST_URL + 'user/setAvatar?token=' +localStorage.getItem('token'), form,  
    {headers: new Headers({'X-Requested-With': 'XMLHttpRequest' })}
    ).catch(this.handleError);
  }

REST_API Php (LARAVEL)

public function setAvatar(Request $request){
        if($request->hasFile("avatar")) {   //  ALWAYS FALSE !!!!
            $avatar = $request->file("avatar");
            $filename = time() . "." . $avatar->getClientOriginalExtension();
            Image::make($avatar)->fit(300)->save(public_path("/uploads/avatars/" . $filename));
            return response()->json(['message' => "Avatar added !"], 200);
        }

        return response()->json(['message' => "Error_setAvatar: No file provided !"], 200);
    }

Content of the Request Payload (As seen from Chrome Inspect/Network)

------WebKitFormBoundary8BxyBbDYFTYpOyDP
Content-Disposition: form-data; name="avatar"

Should be more like...:

Content-Disposition: form-data; name="avatar"; filename="vlc926.png"
Content-Type: image/png

1
  • you can try to use ng2-file-upload. Work nicely for me. Commented Apr 18, 2017 at 2:32

1 Answer 1

2

Turns out Angular2's Http can now send files... And it's super easy !.... I just can't believe there are just no documentation out there showing this ! Except this one. (Credits to MICHAŁ DYMEL)

https://devblog.dymel.pl/2016/09/02/upload-file-image-angular2-aspnetcore/

The HTML

    <input #fileInput type="file"/>
    <button (click)="addFile()">Add</button>

Component.ts

@ViewChild("fileInput") fileInput;

addFile(): void {
let fi = this.fileInput.nativeElement;
if (fi.files && fi.files[0]) {
    let fileToUpload = fi.files[0];
    this.uploadService
        .upload(fileToUpload)
        .subscribe(res => {
            console.log(res);
        });
    }
}

The service.ts

upload(fileToUpload: any) {
    let input = new FormData();
    input.append("file", fileToUpload);

    return this.http.post("/api/uploadFile", input);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Please don't post link-only answers. The links tend to break and make the answers useless. Instead, pull in the relevant information into your answer.
And i did... Hopes this helps others !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.