从Axios请求返回ASP.NET Core API中的下载文件

问题描述 投票:0回答:1

美好的一天,

我正在尝试从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) })

但我只收到这个。没有下载文件。

enter image description here

我希望你能帮助我从我的控制器api下载一个文件。

c# asp.net-web-api asp.net-core axios
1个回答
4
投票

首先,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();
});
© www.soinside.com 2019 - 2024. All rights reserved.