vue项目开发时,需要对文件进行导出操作,这就需要用到下载文件操作,这里使用的是axios进行下载操作。
async exportData() {
var data = qs.stringify({queryParam: this.data.queryParam})
let url = '/openApi/apiorderinfo/export?' + data;
this.downloadLoading = true;
axios.get(url, {
baseURL: window.SITE_CONFIG['apiURL'],
responseType: 'blob', //设置响应的数据类型为一个包含二进制数据的 Blob 对象,必须设置
headers: {
Authorization: 'Bearer ' + Cookies.get('access_token'),
}
}).then(res => {
this.downloadLoading = false
if (!res) {
this.$message.error("下载模板文件失败");
return false;
}
const blob = new Blob([res.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'});
const downloadElement = document.createElement('a');
const href = window.URL.createObjectURL(blob);
let contentDisposition = res.headers['content-disposition']; //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
let patt = new RegExp("filename=([^;]+\\.[^\\.;]+);*");
let result = patt.exec(contentDisposition);
let filename = decodeURI(result[1]);
downloadElement.style.display = 'none';
downloadElement.href = href;
downloadElement.download = filename; //下载后文件名
document.body.appendChild(downloadElement);
downloadElement.click(); //点击下载
document.body.removeChild(downloadElement); //下载完成移除元素
window.URL.revokeObjectURL(href); //释放掉blob对象
}).catch(function (error) { // 请求失败处理
console.log(error);
});
},