在 Angular 6 中使用 FormData 上传文件时出现问题

Problem uploading file with FormData in Angular 6

我正在尝试构建一个文件上传系统,其中 Angular 6 用于 UI,Lumen 用于 API。 当我直接在 Postman 中使用 API 时,文件上传工作正常。 但它不适用于 Angular UI。 我正在使用 FormData 来处理上传,但是 API returns 是我尝试上传的文件的空值。

HTML:

<input type="file" name="document" (change)="onFileChanged($event.target.files)">

Angular代码:

public onFileChanged(files: any): void {
    var file = files[0];
    var fd = new FormData();
    fd.append('document', file);
    this.documentService
        .uploadDocument(this.id, fd)
        .subscribe(
            () => {
                console.log('success');
            },
            () => {
                console.log('failure');
            }
        );
}

我在我的项目中使用了表单数据。看看我的 code.it 可能对你有帮助

       uploadFile(data, index) {
          const formData: FormData = new FormData();
          console.log('formData', formData);

          formData.append('data', this.tableData.caseId);
          formData.append('file', data.filedata);
          this.dashService.uploadAttachment(formData, this.encodedData)
            .subscribe(
              (respData) => {
                this.filesArray.splice(index, 1);
              },
              respError => {
                console.log('respError', respError);
              }
            );
        }
        removeFile(index) {
          this.filesArray.splice(index, 1);
        }

下面是代码中使用的服务。

     uploadAttachment(data, encodedData) {
        return this._http.post(this._url + 'cases/attachment', data, {
          headers: {
            // 'Content-Type': 'multipart/form-data',
            'Accept': 'application/json',
            'Authorization': encodedData
          }
        });
      }

我在服务中使用的内容类型遇到了问题。所以我评论了它并且我的代码工作正常。

好的,我找到问题了!

这是因为我使用的拦截器会向每个请求添加 JSON header,所以它将所有内容都转换为 JSON,这显然是行不通的。所以我只是删除了 header 并且它起作用了。