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

 



posted on 2021-05-13 10:25  blue_hl  阅读(1431)  评论(0编辑  收藏  举报