- 没有文件服务器, 前后端采用文件流方式下载,后端返回二进制乱码时,前端使用blob对象进行处理
2.采用的是axios请求方式 - this.$http.post("download", { fileName: file.filename })
.then(function(response) {
let blob = new Blob([response.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'});
let downloadElement = document.createElement('a');
let href = window.URL.createObjectURL(blob); //创建下载的链接
downloadElement.href = href;
downloadElement.download = 'xxx.xlsx'; //下载后文件名
document.body.appendChild(downloadElement);
downloadElement.click(); //点击下载
document.body.removeChild(downloadElement); //下载完成移除元素
window.URL.revokeObjectURL(href); //释放掉blob对象
})
3.1
this.$http.post("download", { fileName: file.filename } ,{responseType: 'arraybuffer'}) // 或者responseType: 'blob'
.then(function(response) {
let blob = new Blob([response.data], {type: 'application/vnd.ms-excel'});
if (window.navigator.msSaveOrOpenBlob) {
//兼容ie
window.navigator.msSaveBlob(blob, file.filename);
} else {
let downloadElement = document.createElement('a');
let href = window.URL.createObjectURL(blob); //创建下载的链接
downloadElement.href = href;
downloadElement.download = file.filename;//下载后文件名
document.body.appendChild(downloadElement);
//此写法兼容火狐
let evt = document.createEvent("MouseEvents");
evt.initEvent("click", false, false);
downloadElement.dispatchEvent(evt);
document.body.removeChild(downloadElement);
}
})
4.分享链接 https://www.oschina.net/question/3910533_2283267
- 前端处理文件流自动下载并兼容ie9+ https://blog.csdn.net/skye_Z/article/details/81135540
所有评论(0)