vue的axios下载excel时,获取不到Content-Disposition内容,提取文件名
function postDownload(downloadUrl, params, contentType, callback){
let headers = {
'Content-Type': contentType
};
axios(
{
method: "post",
url: downloadUrl,
data: params,
headers: headers,
responseType: "blob", // 指定获取数据的类型为blob
}
).then(
function (response) {
console.log(response);
// 前提是服务端要在header设置Access-Control-Expose-Headers: Content-Disposition
// 前端才能正常获取到Content-Disposition内容
const disposition = response.headers['content-disposition'];
let fileName = disposition.substring(disposition.indexOf('filename=') + 9, disposition.length);
// iso8859-1的字符转换成中文
fileName = decodeURI(escape(fileName));
// 去掉双引号
fileName = fileName.replace(/\"/g, "");
const content = response.data;
console.info("rep:", disposition);
console.info("fileName:", fileName);
// 创建a标签并点击, 即触发下载
let url = window.URL.createObjectURL(new Blob([content]));
let link = document.createElement("a");
link.style.display = "none";
link.href = url;
link.setAttribute("download", fileName);
//link.download = "测试下载文件.xls"
// 模拟
document.body.appendChild(link);
link.click();
// 释放URL 对象
window.URL.revokeObjectURL(link.href);
document.body.removeChild(link)
}
).catch(function (err) {
console.log(err)
})
}
这个语句获取不到
const disposition = response.headers['content-disposition'];
最后找到了解决方法:
只需要在服务器端返回response的header里面设置
Access-Control-Expose-Headers: Content-Disposition
————————————————
版权声明:本文为CSDN博主「不屑哥」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/fuck487/article/details/105122538/