5

I am trying to implement a file download on my react app, the API is a .net core api.

I am using fileSaver js to implement the front end, but it doesnt seem to save the file properly.

My API:

        [Authorize]
        [HttpGet]
        public async Task<IActionResult> DownloadInvoice(string ID)
        {
            var invoiceContent = await this.getfile(ID); 
            //this returns a byte array of the PDF file content
            if (invoiceContent == null)
                return NotFound();
            var stream = new MemoryStream(invoiceContent); //saves it into a stream
            stream.Position = 0;
            return File(stream, "application/octec-stream", $"{invoiceNo}.pdf");
        }

My react code:

    import { saveAs } from 'file-saver';
    axios
    .get(url, {
        headers: {
          'Content-Type': 'application/json',
          responseType: 'blob',
        },
      })
      .then(function(res) {
            var blob = new Blob([res.data], {
                  type: 'application/pdf',
                });

            saveAs(blob, invoice.invoiceNo + '.pdf');
        });
    }}

i tested the API with postman, it returns correct data and i can save the file correctly,

result looks like this in postman, which is correct content of a PDF file:

%PDF-1.6
%����
1 0 obj
<<
/Creator(Telerik Reporting 7.1.13.612 \(http://www.telerik.com/products/reporting.aspx\))
/Producer(Telerik Reporting 7.1.13.612 \(http://www.telerik.com/products/reporting.aspx\))
/CreationDate(D:20190124112008+13'00')
>>
endobj
2 0 obj
<<
/Type/Catalog
/ViewerPreferences 3 0 R
/Pages 4 0 R
>>
endobj
3 0 obj
[bla bla bla....]

but when its been saved via blob in react, it creates a "valid" pdf file with blank page. with an increased file size (it goes from 43k to 76k)..

I wonder if someone know what was wrong about this implementation and could point me to the right direction.

Thanks a lot

1 Answers1

2

OK, the issue is this:

 .get(url, {
        headers: {
          'Content-Type': 'application/json',
        },
        responseType: 'blob', ////move this line out of the headers....
      })