[英]Excel download from Asp.Net Web API using Axios post method
我有一個返回excel文件的操作。
[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; }
}
我正在使用帶有 Axios 庫的 react js 來進行 Web API 調用。 現在的問題是,如何使用 axios post call 調用上述 API,從而觸發瀏覽器下載 API 返回的 excel 並保存它?
我已經嘗試了以下嘗試,但似乎 axios 調用中的響應對象沒有任何內容,但我可以在“網絡”選項卡下的瀏覽器響應中看到 excel 內容。 所以看起來瀏覽器正在獲取文件內容但沒有保存它。 知道我缺少什么嗎?
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
}
});
提前致謝。
我知道對你來說可能為時已晚。 只是回復以防其他人需要。 您可以嘗試將代碼更改為以下內容。
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();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.