在React js中下载/保存文件 [英] Download/Save file in react js

查看:1208
本文介绍了在React js中下载/保存文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该如何保存来自api的响应,该响应会为我提供具有数据和名称的excel文件?

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.

https://mydomain.dev.com/export

我在网络上浏览了多篇文章,但是到处都有解释,将数据另存为excel文件在客户端,这不是我的情况.对我来说,文件类型和名称已经在服务器端确定了,我只需要照原样保存即可.

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.

非常感谢

推荐答案

这是我通常的处理方式:

Here's how I usually handle this:

我首先获取文件,然后使用 downloadjs 下载blob

I start out by fetching the file and then use downloadjs to download the 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");  
}

这篇关于在React js中下载/保存文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆