Angular 2 - 图片上传,文件未上传到后端(未列出错误)

Angular 2 - Image upload , File not getting uploaded to backend (no error listed)

我正在尝试在 angular 2 中上传图片,我没有列出任何错误,但是文件添加的位置没有变化,下面给出了详细代码

**.ts**
............
  onFileChange(event) {
    if(event.target.files.length > 0) {
      let file = event.target.files[0];
      this.fileName = file.name;
      this.imageUpload['upload'] = this.fileName;
      this.form.get('upload').setValue(file);
      console.log(file);
      console.log('filename',this.fileName);


    }
  }

 private prepareSave(): any {
    let inputVal = new FormData();
    inputVal.append('upload', this.form.get('upload').value,this.imageUpload['upload']);
    console.log(inputVal);
    return inputVal;
  }

  onSubmit() {
    this.imageUpload['upload'] = this.fileName;
    const formModel = this.prepareSave();
    this.loading = true;

    var body = formModel;
    let url = this.ImageUploadURL;
    let headers = new Headers({ 'Content-Type': 'multipart/form-data' ,'Authorization': 'Bearer ' + this.accountsService.accessToken });
    let options = new RequestOptions({ headers: headers });

    console.log(options);
    console.log(body);
    console.log(url);
    // In a real-world app you'd have a http request / service call here like
     return this.http.post(url, body, options)
          .catch(error => Observable.throw(error))
          .subscribe(
              data => console.log('success'),
              error => console.log(error)

        )
  }
...............

在控制台中获取成功

方法是 post 与 url 和 { 上传:"" }

在网络中我得到

想要的部分没有变化可能是什么错误?

还有其他方法吗?

表格编码需要multipart/form-data而不是form-data

试试这个改变:

let headers = new Headers();
headers.set('Content-Type', 'multipart/form-data');
headers.set('Authorization', 'Bearer' + blah);

如果你想重构你的组件,有一个稍微不同的方法:

https://gist.github.com/arciisine/ee57727e56cbc5e83739b2c24fd69658

在 Angular 中,当使用 multipart form-data 并且您正在使用 FormData object 时,您不得指定 Content-Type header。

这样做是在阻止 http 堆栈将其设置为正确的值 MUST include the boundary value

只需删除内容类型 header 并让格式化程序为您处理,您应该没问题。