react 文件下载

2021/5/13 10:58:22

本文主要是介绍react 文件下载,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

如果想通过纯前端技术实现文件下载,直接把a标签的href属性设置为文件路径即可

//downloadSrc即为接口的地址即可
<a href={downloadSrc}>
<Button>Download</Button>
</a>

但是后端传的是文件流,这样下载的是markDown文件,如果想转换成其他格式文件,就要解析文件流,然后通过a标签下载解析出来的数据。

// 下载服务的Markdown文件
export async function downloadMDService() {
return request(downloadSrc, {
method: 'get',
params,
responseType: 'blob',//必须加
});
}
const downloadFn = async () => {
const res = await downloadMDService();
if (res) {
const url = window.URL.createObjectURL(new Blob([res]));
const link = document.createElement('a');//创建a标签
link.style.display = 'none';
link.href = url;////设置a标签路径
link.download = 'file';//设置文件名
document.body.appendChild(link);
link.click();
URL.revokeObjectURL(link.href); // 释放 URL对象
document.body.removeChild(link);
}
};

 





这篇关于react 文件下载的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程