1

我在 Postman 上测试了我的上传 API,它可以工作,但是在我的应用程序(Angular 6 + .net-core 2.1)中,网络总是返回错误 415 unsupported media type,因为Content-Type请求标头总是application/JSON. 基本上,我使用httpClient将 FormData 与端点中的 2 个参数一起返回到 IFormFile 中的后端。我在另一个使用 Angular 5 + .net-core 2.0 的应用程序中有相同的代码,它工作得很好。因此,我不知道 Angular 6 是否有任何重大更改。有人有建议吗?

API服务:

  uploadIcoFile(icoGuid: any, category: any, file: any) {
    const headers = new HttpHeaders({ 'Content-Type': 'multipart/form-data' });
    return this.httpClient.post<any>(this.apiUrl + `ico/upload-file/${icoGuid}/${category}`, file, { headers: headers })
      .pipe(
        catchError(this.handleError)
      );
  }

上传组件:

  upload(event: any) {
    const fileBrowser = this.myInputVariable.nativeElement;
    if (fileBrowser.files) {
      if (fileBrowser.files[0].size < 10000) {    // 16000
        this.sharedFunctionsService.showWarningToast('File is too small, needs to be at least 10KB');
      } else {
        const formData: FormData = new FormData();
        formData.append('file', fileBrowser.files[0]);
        this._uploadIcoFile(this.icoId, this.type, formData);
      }
    }
  }

  _uploadIcoFile(icoGuid: any, category: any, file: FormData) {
    this.loading = true;
    this.apiService.uploadIcoFile(icoGuid, category, file).subscribe(data => {
      this.loading = false;
      this.fileUploaded.emit(true);
      this.reset();
      this.sharedFunctionsService.showSuccessToast('File successfully uploaded');
    },
      (error) => {
        this.loading = false;
        this.sharedFunctionsService.showErrorToast('An error happened when trying to upload file');
      });
  }

控制器:

[HttpPost("upload-file/{icoGuid}/{category}")]
[Authorize]
[Authorize(Policy = "Active")]
[ProducesResponseType(typeof(int), 200)]
public async Task<IActionResult> UploadIcoAttachment(Guid icoGuid, string category, IFormFile file)
{
  return Ok(await Mediator.Send(new UploadIcoAttachmentsCommand() {
    File = file,
    FileCategory = (FileCategory)Enum.Parse(typeof(FileCategory), category),
    AccountId = GetAccountId(),
    IcoGuid = icoGuid
  }));
}
4

0 回答 0