如何替换Angular2 Http上传文件?

时间:2017-04-18 14:12:27

标签: rest angular file-upload angular-http ng-file-upload

以下代码尝试从Angular2应用程序发送文件。它总是在REST API中最终无法识别它正在接收的请求中的文件。 (即使内容接触到了!)

在花费数小时搜索StackOverflow和无数其他在线资源后,我得出结论,最新版本的Angular2 Http模块/服务现在应该能够处理文件上传。 (过去它无法做到这一点的事实真是太棒了!) 见article甚至this git sample

如果我要使用像ng2-file-upload这样的外部库,它需要能够用尽可能少的修改替换Angular2 :: Http到下面的代码。 (即我无法更改HTML表单。)

Component.html



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

Component.ts

&#13;
&#13;
  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);
            }

          );
        }
  }
&#13;
&#13;
&#13;

authService.ts

&#13;
&#13;
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);
  }
&#13;
&#13;
&#13;

REST_API Php(LARAVEL)

&#13;
&#13;
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);
    }
&#13;
&#13;
&#13;

请求有效负载的内容(从Chrome Inspect / Network看到)

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

应该更像......:

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

1 个答案:

答案 0 :(得分:0)

原来Angular2的Http现在可以发送文件......而且它非常容易!....我无法相信没有文档可以显示这个! Except this one. (Credits to MICHAŁ DYMEL)

HTML

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

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);
        });
    }
}

service.ts

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

    return this.http.post("/api/uploadFile", input);
}