【问题标题】:Excel download from Asp.Net Web API using Axios post method使用 Axios post 方法从 Asp.Net Web API 下载 Excel
【发布时间】:2018-06-11 04:58:02
【问题描述】:

我有一个返回 excel 文件的操作。

[HttpPost]
public async Task<IActionResult> Export([FromBody] QueryParameters qp)
{                
    var stream = _service.GetExcel(qp);
    var exportFileName = "MyExcel";
    return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", exportFileName);                      
}
//
public class QueryParameters
{
    public int From { get; set; }           
    public int Page { get; set; } 
    public int Size { get; set; } 
}

我正在使用带有 Axios 库的 react js 来进行 Web API 调用。现在这里的问题是,如何使用 axios post call 来调用上面的 API,触发浏览器下载 API 返回的 excel 并保存?

我在下面给出了尝试,但在 axios 调用中的响应对象中似乎没有任何内容,但我可以在“网络”选项卡下的浏览器响应中看到 excel 内容。所以看起来浏览器正在获取文件内容但没有保存它。知道我错过了什么吗?

const requestBody = {
    From: 10,
    page:2,
    Size:10
};

axios.request('POST', 'https://myexport.dev.com/export', requestBody )
.then(response => {data:response.data}) //response is comming as null here
.catch((error) => {
    //handle error
}           
});

提前致谢。

【问题讨论】:

    标签: javascript reactjs asp.net-web-api axios


    【解决方案1】:

    我知道这对你来说可能为时已晚。只是回复以防其他人需要。您可以尝试将您的代码更改为以下内容。

    axios.request({method:'POST', url:'https://myexport.dev.com/export',
    data:{someKey: someValue}, responseType: 'blob' })
    .then((response) => {
       const url = window.URL.createObjectURL(new Blob([responseData]));
       const link = document.createElement('a');
       link.href = url;
       link.setAttribute('download', 'fileName.xlsx');
       document.body.appendChild(link);
       link.click();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-01
      • 1970-01-01
      • 2021-01-11
      • 2021-06-02
      相关资源
      最近更新 更多