解决vue使用axios post 方法导出excel问题

此问题花了大半天时间解决,记录下以供查阅。

解决问题步骤如下:

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请求方法,就好啦!!!太坑了,总算解决了。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值