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

Posted

技术标签:

【中文标题】从 Axios 请求返回 ASP.NET Core API 中的下载文件【英文标题】:Return Download File in ASP.NET Core API from Axios Request 【发布时间】:2019-08-03 22:00:10 【问题描述】:

大家好,

我正在尝试通过 Axios 请求从 ASP.NET Core Web API 下载文件。

这是我的示例 API 方法。 (代码来自*** 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 下载一个文件。

【问题讨论】:

1) File 接受byte[]。将 byte[] 包装在 MemoryStream 中是没有意义的,只会使内存利用率翻倍。 2) 如果文件是 PDF,为什么不使用 PDF mimetype 返回它? (application/pdf) 【参考方案1】:

这里是:

    [HttpPost]
    [Route("")]
    public FileContentResult Download()
     
    ... 
    return File("thisFile"); 
    

【讨论】:

【参考方案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();
);

【讨论】:

它与post 一起工作得非常好,先生。谢谢你,先生。它现在可以工作了:) @AppleCiderYummy 这不是重点。它应该是一个 get 请求,因为 REST 规范如何定义 get 和 post 请求的作用。尽管在技术上可以使用任何动词执行任何操作,但 Get 请求从服务器读取数据。 Post 请求用于在服务器上创建新资源。通过使用帖子来执行应该得到的东西,就像在英语中使用错误的单词并且仍然让人们理解您要说的内容。再加上以后更难以推理代码。

以上是关于从 Axios 请求返回 ASP.NET Core API 中的下载文件的主要内容,如果未能解决你的问题,请参考以下文章

在 ASP.NET Core 中使用 Axios 和 Vue.JS 进行多文件上传

每当我发送包含 Bearer 令牌的请求时,ASP.Net Core API 总是返回 401 未授权

ASP.NET Core HttpClient 请求在 webapi 返回 406 时返回 200

配置方法中的asp net core请求服务返回null

以 axios.post 形式接收 asp.net core web api 中的数组

ASP.NET Core RC2 IIS 在选项请求上返回 502