1

I have a WebAPI that has a method which makes an Excel file and returns it using File().

In my Angular app I subscribe to the response and download the file using blob. But I am getting an error in the browser console which says it can't parse the response to a JSON.

Why does it want to parse the response to a JSON? And how to fix this problem?

API Controller:

 [HttpPost]
 public IActionResult QRGenerator(QRCode qrCode)
 {
      string wwwrootPath = _hostingEnvironment.WebRootPath;

       var QrCodes = new List<QRCode>();
       QrCodes.Add(qrCode);
       ExcelGenerator generator = new ExcelGenerator();
       var fileName = generator.GeneratePrintableSheets(QrCodes, wwwrootPath);
       var path = Path.Combine(wwwrootPath, fileName);
       return DownloadFile(fileName, wwwrootPath);   
  }

  public IActionResult DownloadFile(string fileName, string wwwrootPath)
  {
      var path = Path.Combine(wwwrootPath, fileName);
      var content = System.IO.File.ReadAllBytes(path);
      return File(content, "application/vnd.ms-excel", fileName);
   }

Angular Component:

  createQR(qrCode: QRCode) {
    let formData: FormData = new FormData();
    this.singleQr.CreateSingleQR(formData).subscribe(data => {
      this.downloadFile(data);
      console.log(data);
    });
  }

 downloadFile(data: any){
   var blob = new Blob([data], { type: 'application/vnd.ms-excel' });
   var url= window.URL.createObjectURL(blob);
   window.open(url);
 }

And for completion sake the Angular Service:

 CreateSingleQR(formdata: FormData) {
    return this.http.post(this.qrUrl, formdata);
  }

Browser Error

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Daniël Krux
  • 13
  • 1
  • 6

1 Answers1

2

You need to tell Angular that the response is not JSON so it will not try to parse it. Try changing your CreateSingleQR code to:

CreateSingleQR(formdata: FormData) {
    return this.http.post(this.qrUrl, formdata, { responseType: ResponseContentType.Blob } );
}
Simply Ged
  • 8,250
  • 11
  • 32
  • 40