使用POST下载文件

一直以来,JS都没有比较好的可以直接处理二进制的方法。而Blob的存在,允许我们可以通过JS直接操作二进制数据。
一、下载

util.fetchDownload= function (opt,data) {
return fetch(opt.url,{
method: "POST",
headers: {
'Content-Type': 'application/json',
},
mode: "cors",
body: JSON.stringify(data),
credentials: 'include'
}).then(resp => resp.blob().then(blob => {
const disposition = resp.headers.get("content-disposition");
const match = disposition ? disposition.match(/attachment; filename="(.+)"/i) : null;
const filename = match && match.length > 1 ? match[1] : snTime + ".xls";
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, filename); //兼容ie10
} else {
var a = document.createElement('a');
document.body.appendChild(a) //兼容火狐,将a标签添加到body当中
var url = window.URL.createObjectURL(blob); // 获取 blob 本地文件连接 (blob 为纯二进制对象,不能够直接保存到磁盘上)
a.href = url;
a.download = filename;
a.target='_blank' // a标签增加target属性
a.click();
a.remove() //移除a标签
window.URL.revokeObjectURL(url);
}
}).then(function () {
opt.success()
}))

};


posted @ 2019-01-29 15:52  空山竹语  阅读(217)  评论(0编辑  收藏  举报