通常下载通过document.createElement创建虚拟a标签
function downloadFileUrl(val, url, fileName) {
if (isVal) return false;
let url= `${process.env.BASE_URL}/${url}`;
const elink = document.createElement('a');
elink.href = url;
elink.target = '_self'; // 当前也 target打开新页面
// elink.setAttribute('download', fileName);
let name = fileName ? val.split('"')[1] : '输出结果';
elink.download = `${name}-${fileName}`; //自定义文件名
elink.style.display = 'none';
document.body.appendChild(elink);
message.success(`${val} ${fileName} 下载成功`);
setTimeout(() => {
elink.click(); //模拟出发a 点击事件
document.body.removeChild(elink); // 删除a
}, 66);
}
在使用a标签下载文件时,download属性可以更改下载的文件名,但是当a标签的下载链接跨域时,download属性将不会生效,原因是浏览器无法获取到文件,不能对他进行更改
注意:html5 新特性a标签download属性只支持谷歌和火狐
在谷歌和火狐浏览器a标签download属性修改文件名失效的原因:不同源,访问的域名和href的域名要一致。
解决方法:
使用HTML5 Blob实现文件下载,先把文件以bobl的形式下载到当前页面,再创建a标签。
function downloadFileUrl(val, url, fileName) { // val是标题 、url 是地址、fileName区分批量还是单个下载参数
if (isVal) return false;
let aUrl = `${process.env.BASE_URL}/${url}`;
const x = new XMLHttpRequest();
x.open('GET', aUrl, true);
x.responseType = 'blob';
x.onload = function (e) {
const url = window.URL.createObjectURL(x.response);
const elink = document.createElement('a');
elink.href = url;
elink.target = '_self'; // 当前也 target打开新页面
// elink.setAttribute('download', fileName);
let name = fileName ? val.split('"')[1] : '输出结果'; //此处根据自己的情况修改
elink.download = `${name}-${fileName}`;
elink.style.display = 'none';
document.body.appendChild(elink);
message.success(`${val} ${fileName} 下载成功`);
setTimeout(() => {
elink.click();
document.body.removeChild(elink);
}, 66);
};
x.send();
}