前端小白,仅供参考,个人实测可以
今天遇到了一个新的需求,添加一个下载按钮,下载一个后缀为crt格式的文件
正常逻辑是后端给到一个下载的接口地址,点击事件内直接调用对应接口
但是也有例外情况,后端给的是一个文件流地址
如图↓
![](https://img-blog.csdnimg.cn/img_convert/6e5869e1b7d0a3d45c9f6ad56b983517.png)
也就是说你调用接口拿到的并不是一个文件,而是一个文件的内容(这里是我自己理解的)
那这种应该怎么才能把数据变成文件并下载下来呢
首先要配置你的axios或者fetch请求
![](https://img-blog.csdnimg.cn/img_convert/781dbd8cbee3ea5de333bdb0ba4aa2d9.png)
可以写成下面这样在接口文件内,这样直接调用getExample就可以了
![](https://img-blog.csdnimg.cn/img_convert/223d78895aa9e9ad4275f18032036f57.png)
然后直接照抄下面的代码 封装成一个函数 然后在接口的then处理函数里直接处理对应数据,原理是创建一个类文件对象 注意第四行要改成你要下载的文件的名字(ps:目前没发现可以随机下载任意文件名字的配置,也就是说这里是写死的)
export default (res: any) => {
let blob = new Blob([res.data]);
// 提取文件名
let contentDisposition: any = "";
if (res.headers["content-disposition"])
contentDisposition = res.headers["content-disposition"];
if (res.headers["Content-disposition"])
contentDisposition = res.headers["Content-disposition"];
const err = contentDisposition.match(/err=(.*)/);
if (err && err[1]) {
message.error(decodeURI(err[1]));
return;
}
const fileName = contentDisposition.match(/filename=(.*)/)[1];
if (typeof window.navigator.msSaveBlob !== "undefined") {
// 兼容IE,window.navigator.msSaveBlob:以本地方式保存文件
window.navigator.msSaveBlob(blob, decodeURI(fileName));
} else {
// 创建新的URL并指向File对象或者Blob对象的地址
const blobURL = window.URL.createObjectURL(blob);
// 创建a标签,用于跳转至下载链接
const tempLink = document.createElement("a");
tempLink.style.display = "none";
tempLink.href = blobURL;
tempLink.setAttribute("download", decodeURI(fileName));
// 兼容:某些浏览器不支持HTML5的download属性
if (typeof tempLink.download === "undefined") {
tempLink.setAttribute("target", "_blank");
}
// 挂载a标签
document.body.appendChild(tempLink);
tempLink.click();
document.body.removeChild(tempLink);
// 释放blob URL地址
window.URL.revokeObjectURL(blobURL);
}
return true;
};
当然,如果直接是可以下载文件的地址 用<a>标签的downLoad的属性,或者window.open(“下载地址”)来完成下载,这里不再一一赘述
第一篇文档
如有问题请留言~ 欢迎交流