比较简单,直接上代码
方法一:接口返回型
// 创建blob对象,解析流数据
const blob = new Blob([res], {//res为接口返回数据流
// 设置返回的文件类型
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
});
//下载方法
const a = document.createElement("a"); // 创建a标签,模拟点击事件
const URL = window.URL || window.webkitURL; // 兼容webkix浏览器,处理webkit浏览器中href自动添加blob前缀,默认在浏览器打开而不是下载
const herf = URL.createObjectURL(blob); // 创建URL 对象
a.href = herf; // 下载链接
a.download = "示例"; // 下载文件名;若后端没有返回,可以自己写'文件.xlsx'
document.body.appendChild(a);
a.click(); // 点击a标签下载
document.body.removeChild(a); // 移除URL 对象
window.URL.revokeObjectURL(herf);
方法二:URL链接型
const x = new XMLHttpRequest();
x.open("GET", url, true);//url文件地址,必须填写
x.responseType = "blob";
x.onload = e => {
// 会创建一个 DOMString,其中包含一个表示参数中给出的对象的URL。这个 URL 的生命周期和创建它的窗口中的 document 绑定。这个新的URL 对象表示指定的 File 对象或 Blob 对象。
const urlF = window.URL.createObjectURL(x.response);
const a = document.createElement("a");
a.href = urlF;
a.download = `${name}`;//name文件名,没有就自己定义
a.click();
};
x.send();
常见的文件类型大观:
application/msword //word(.doc)
application/vnd.ms-powerpoint //powerpoint(.ppt)
application/vnd.ms-excel //excel(.xls)
application/vnd.openxmlformats-officedocument.wordprocessingml.document //word(.docx)
application/vnd.openxmlformats-officedocument.presentationml.presentation //powerpoint(.pptx)
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet //excel(.xlsx)
application/x-rar-compressed //rar
application/zip //zip
application/pdf //pdf
video/* // 视频文件
image/* //图片文件
text/plain //纯文本
text/css //css文件
text/html //html文件
text/x-java-source //java源代码
text/x-csrc //c源代码
text/x-c++src //c++源代码
7577





