如果想通过纯前端技术实现文件下载,直接把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);
}
};

 



相关文章:

  • 2022-12-23
  • 2022-01-11
  • 2022-12-23
  • 2022-12-23
  • 2021-10-14
  • 2021-11-23
  • 2021-12-06
  • 2021-12-26
猜你喜欢
  • 2021-07-16
  • 2021-07-23
  • 2021-05-08
  • 2021-05-28
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案