比较简单,直接上代码
// 创建blob对象,解析流数据
const blob = new Blob([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);
常见的文件类型:
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++源代码