Angular 6 - file upload unsupported media type 415

2.1k views Asked by At

I tested my upload API on Postman, it works, but in my app (Angular 6 + .net-core 2.1), the network always returns error 415 unsupported media type because the Content-Type in request headers is always application/JSON. Basically, I use httpClient to return the FormData to Backend in IFormFile along with 2 parameters in the endpoint. I had the same code in another app with Angular 5 + .net-core 2.0 and it works just fine. Therefore, I have no idea if there are any breaking changes on Angular 6. Anyone has suggestions?

API Service:

  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 component:

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

Controller:

[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

There are 0 answers