美好的一天,
我正在尝试从Axios Request中下载ASP.NET Core Web API中的文件。
这是我的示例API方法。 (基于此stackoverflow question的代码)
[HttpPost("download")]
public async Task<IActionResult> DownloadFile(){
...
return File(new MemoryStream(mypdfbyte), "application/octet-stream", "myfile.pdf");
}
这是我的样本axios请求。
axios.post(`api/products/download`).then(response=>{
console.log(response.data)
}).catch(error=>{ console.log(error) })
但我只收到这个。没有下载文件。
我希望你能帮助我从我的控制器api下载一个文件。
首先,DownloadFile应该是HttpGet而不是HttpPost。那你的axios请求应该是这样的
axios({
url: 'http://localhost:5000/api/products/download',
method: 'GET',
responseType: 'blob', // important
}).then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.pdf');
document.body.appendChild(link);
link.click();
});