解决vue使用axios post 方法导出excel问题
此问题花了大半天时间解决,记录下以供查阅。解决问题步骤如下:1.使用axios中的post传递参数,后台导出excel数据。api接口调用如下:exportPosition(data) {let url = `${EXPORT_POSITION}`;returnVueHttp.$http.post(url,data,{responseType: 'blob'}...
·
此问题花了大半天时间解决,记录下以供查阅。
解决问题步骤如下:
1.使用axios中的post传递参数,后台导出excel数据。api接口调用如下:
exportPosition(data) {
let url = `${EXPORT_POSITION}`;
return VueHttp.$http.post(url,data,{responseType: 'blob'}); //必须设置 responseType
//return VueHttp.$http.post(url,data,{responseType: 'arraybuffer'})
},
2.后台设置response的content-type为:content-type:application/octet-stream;charset:utf-8
3.下载文件。根据第一步的设置请求后的格式如下:
一定要注意此处返回的data,如果是text格式就说明有问题!!!
下载的方法如下:
//下载excel
export function exportExl(res,mime) {
if(!res) return;
//let fileName = decodeURI(res.headers['content-disposition'].split('=')[1]),
//let filename = '导出职位.xls',
let filename = res.headers['content-disposition']?res.headers("Content-Disposition").split(";")[1].split("filename=")[1]:'职位导出表.xls',
//let filename = '导出职位.xls',
blob = res.data;
//blob = new Blob([res.data], {type: mime || 'application/octet-stream'});
if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE workaround for "HTML7007: One or more blob URLs were
// revoked by closing the blob for which they were created.
// These URLs will no longer resolve as the data backing
// the URL has been freed."
window.navigator.msSaveBlob(blob, filename);
}
else {
var blobURL = window.URL.createObjectURL(blob);
var tempLink = document.createElement('a');
tempLink.style.display = 'none';
tempLink.href = blobURL;
tempLink.setAttribute('download', filename);
// Safari thinks _blank anchor are pop ups. We only want to set _blank
// target if the browser does not support the HTML5 download attribute.
// This allows you to download files in desktop safari if pop up blocking
// is enabled.
if (typeof tempLink.download === 'undefined') {
tempLink.setAttribute('target', '_blank');
}
document.body.appendChild(tempLink);
tempLink.click();
document.body.removeChild(tempLink);
window.URL.revokeObjectURL(blobURL);
}
}
总结:最后发现问题是mockjs问题,屏蔽了当前页面的mock请求方法,就好啦!!!太坑了,总算解决了。
更多推荐
已为社区贡献4条内容
所有评论(0)