App*_*mmy 2 c# asp.net-web-api asp.net-core axios
大家好
我正在尝试从Axios Request从ASP.NET Core Web API下载文件。
这是我的示例API方法。(基于此stackoverflow问题的代码)
[HttpPost("download")]
public async Task<IActionResult> DownloadFile(){
...
return File(new MemoryStream(mypdfbyte), "application/octet-stream", "myfile.pdf");
}
Run Code Online (Sandbox Code Playgroud)
这是我的示例axios请求。
axios.post(`api/products/download`).then(response=>{
console.log(response.data)
}).catch(error=>{ console.log(error) })
Run Code Online (Sandbox Code Playgroud)
但是我只收到这个。没有下载文件出现。
希望您能帮助我从控制器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();
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
609 次 |
| 最近记录: |