简体   繁体   English

使用 Axios post 方法从 Asp.Net Web API 下载 Excel

[英]Excel download from Asp.Net Web API using Axios post method

I have an action which returns excel file.我有一个返回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; } 
}

I am using react js with Axios library to make the web API calls.我正在使用带有 Axios 库的 react js 来进行 Web API 调用。 Now the question here is, how I can make a call to above API using axios post call which triggers the browser to download the excel returned by API and save it?现在的问题是,如何使用 axios post call 调用上述 API,从而触发浏览器下载 API 返回的 excel 并保存它?

I have given below try but it seems nothing is coming in response object in axios call but I could see the excel content in browsers response under Networks tab.我已经尝试了以下尝试,但似乎 axios 调用中的响应对象没有任何内容,但我可以在“网络”选项卡下的浏览器响应中看到 excel 内容。 So it looks like the browser is getting the file content but not saving it.所以看起来浏览器正在获取文件内容但没有保存它。 Any idea what I am missing, please?知道我缺少什么吗?

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
}           
});

Thanks in advance.提前致谢。

I know it might be too late for you.我知道对你来说可能为时已晚。 Just reply in case someone else needed.只是回复以防其他人需要。 You can try to change your code to the following.您可以尝试将代码更改为以下内容。

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();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM