伙计们,
我正在尝试从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下载文件。
答案 0 :(得分:2)
首先,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();
});
答案 1 :(得分:0)
这里是:
[HttpPost]
[Route("")]
public FileContentResult Download()
{
...
return File("thisFile");
}