Angular 6-文件上传不受支持的媒体类型415

时间:2018-11-14 10:34:01

标签: angular .net-core http-status-code-415

我在Postman上测试了我的上传API,它可以工作,但是在我的应用程序(Angular 6 + .net-core 2.1)中,网络始终返回错误415不支持的媒体类型,因为请求标头中的Content-Type始终是application/JSON。基本上,我使用httpClient将FormData连同端点中的2个参数一起返回IFormFile中的Backend。我在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
  }));
}

0 个答案:

没有答案