Reputation: 1569
I have an action which returns excel file.
[HttpPost]
public async Task<IActionResult> Export([FromBody] QueryParameters qp)
{
var stream = _service.GetExcel(qp);
var exportFileName = "MyExcel";
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", exportFileName);
}
//
public class QueryParameters
{
public int From { get; set; }
public int Page { get; set; }
public int Size { get; set; }
}
I am using react js with Axios library to make the web API calls. Now the question here is, how I can make a call to above API using axios post call which triggers the browser to download the excel returned by API and save it?
I have given below try but it seems nothing is coming in response object in axios call but I could see the excel content in browsers response under Networks tab. So it looks like the browser is getting the file content but not saving it. Any idea what I am missing, please?
const requestBody = {
From: 10,
page:2,
Size:10
};
axios.request('POST', 'https://myexport.dev.com/export', requestBody )
.then(response => {data:response.data}) //response is comming as null here
.catch((error) => {
//handle error
}
});
Thanks in advance.
Upvotes: 1
Views: 1238
Reputation: 514
I know it might be too late for you. Just reply in case someone else needed. You can try to change your code to the following.
axios.request({method:'POST', url:'https://myexport.dev.com/export',
data:{someKey: someValue}, responseType: 'blob' })
.then((response) => {
const url = window.URL.createObjectURL(new Blob([responseData]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'fileName.xlsx');
document.body.appendChild(link);
link.click();
});
Upvotes: 1