如何替换Angular2 Http上传文件?

How to replace Angular2 Http to upload files?

以下代码尝试从 Angular2 应用程序发送文件。它总是以 REST API 结束,无法识别它正在接收的请求中的文件。 (即使内容接缝在那里!)

在花费数小时搜索 Whosebug 和无数其他在线资源后,我得出结论,最新版本的 Angular2 Http module/service 现在应该能够处理文件上传。 (过去无法做到这一点真是太神奇了!) 看到这个 article or even 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)"  >
            

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

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

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

应该更像是...:[=​​17=]

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

原来 Angular2 的 Http 现在可以发送文件了……而且超级简单!……我简直不敢相信那里没有文档显示这一点! Except this one. (Credits to MICHAŁ DYMEL)

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

service.ts

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

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