Reputation: 515
I am trying to save a file on the client side of my react application. The data is obtained from my API Controller called DownloadDocument. I am returning FileSreamResult from my DownloadDocument method. FileStreamResult reads the data and writes it to the response in the react API. The network tab gets a response, but when i log the response i get a response of null. I am using file-saver to try and save the file. https://www.npmjs.com/package/file-saver.
Does anyone have any recommendations on what the issue is or if there is a better way of doing?
My action in the controller:
The issue that i am having is that my response for the react api is coming back null.
[HttpGet("{documentId}")]
[AcceptVerbs("OPTIONS", "GET")]
[AllowAnonymous]
public async Task<IActionResult> DownloadDocument(int documentId)
{
if (documentId != 0)
{
var document = await service.DownloadDocumentAsync(documentId);
var documentResponse = File(document, "application/octet-stream");
return documentResponse;
}
return BadRequest("Document id is not valid");
}
react application.
api.indexes.downloadDocument(clones)
.then(response=>{
console.log(response)
let FileSaver = require('file-saver');
let blob = new Blob([response], {type: "application/octet-stream"});
let filename ="testdownload"
FileSaver.saveAs(blob, filename)
Thanks for the help.
Upvotes: 2
Views: 2976
Reputation: 515
I needed to add this to the header. responseType: 'blob'
this article explains it well https://medium.com/@fakiolinho/handle-blobs-requests-with-axios-the-right-way-bb905bdb1c04
Upvotes: 1