Blob 对象表示一个不可变、原始数据的类文件对象。它的数据可以按文本或二进制的格式进行读取,也可以转换成 ReadableStream 来用于数据操作。
Blob 表示的不一定是 JavaScript 原生格式的数据。File 接口基于 Blob,继承了 blob 的功能并将其扩展以支持用户系统上的文件。
官方关于blob的介绍
附件下载封装
//附件下载
export const fileDownload = file => {
getDownload(allUrl.normal.downloadFile, { fileCode: file.fileCode }).then(res => {
if (res.status === 200) {
let fileName = res.headers["content-disposition"].split(";")[1].split("filename=")[1];
// 文件名称解码
let name = decodeURI(fileName);
const blob = new Blob([res.data]);
// ie兼容
if (window.navigator.msSaveOrOpenBlob) {
//兼容 IE & EDGE
navigator.msSaveBlob(blob, name);
}
// 创建一个临时的URL对象
let url = window.URL.createObjectURL(blob);
// 创建一个<a>标签
let link = document.createElement("a");
link.href = url;
link.setAttribute("download", name); // 设置下载文件的文件名,注意要包含正确的扩展名
// 模拟点击下载链接
document.body.appendChild(link);
link.click();
// 清理临时URL对象
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
}
});
};
文件预览 (wps)
// wps文件预览
export const preview = file => {
get(allUrl.normal.previewFile, { fileCode: file.fileCode }).then(res => {
if (!res.success || res.code !== 200) {
message.error(res.msg);
} else {
// 根据返回地址跳转
// 创建一个a标签,a标签的href设置为此外链,ref设置为noreferrer,然后插入到body里,执行a标签的点击事件
let a = document.createElement("a");
a.setAttribute("href", res.data);
// 打开新页面
a.setAttribute("target", "_blank");
a.setAttribute("id", "ftm-link");
// 必须配置noreferrer才能直接打开
a.setAttribute("rel", "noreferrer");
document.body.appendChild(a);
a.click();
const aNode = document.getElementById("ftm-link");
if (aNode) {
document.body.removeChild(aNode);
}
}
});
};
get() 方法和 getDownLoad() 是基于axios 的请求 ,查看 。