javascript 在 react js 中下载/保存文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48019130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Download/Save file in react js
提问by Parashuram
How can i save the response from api which gives me excel file with data and name ?
如何保存来自 api 的响应,该响应为我提供了带有数据和名称的 excel 文件?
I have below api which gives me the excel file and i have to save it at default location as is.
我有下面的 api,它给了我 excel 文件,我必须按原样将它保存在默认位置。
https://mydomain.dev.com/export
I have gone through the multiple articles on the web but everywhere its explained to save the data as excel file at client side which is not the my case. For me, file type and name is already decided at server side and i have to just save as is.
我已经浏览了网络上的多篇文章,但到处都解释了将数据保存为客户端的 excel 文件,这不是我的情况。对我来说,文件类型和名称已经在服务器端决定,我必须按原样保存。
Thanks a lot in advance
非常感谢提前
回答by Roman Romanovsky
I always use this script to do this:
我总是使用这个脚本来做到这一点:
function downloadFile(absoluteUrl) {
var link = document.createElement('a');
link.href = absoluteUrl;
link.download = 'true';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
delete link;
};
So just :
所以就 :
downloadFile("https://mydomain.dev.com/export");
It is working, but i hope that there is better solution.
它正在工作,但我希望有更好的解决方案。
回答by Jo?o Cunha
Here's how I usually handle this:
我通常是这样处理的:
I start out by fetching the file and then use downloadjsto download the blob
我首先获取文件,然后使用downloadjs下载 blob
async downloadFile() {
const res = await fetch("https://mydomain.dev.com/export");
const blob = res.blob();
// from downloadjs it will download your file
download(blob, "file.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}

