一、正常情况下,我们都如此下载文件并修改文件名,在a标签上面添加download属性,由于a.download跨域会失效,上面代码只可同域实现
二、通过blob可以实现跨域下载并修改文件名
downloadFile(item) {//点击方法
var url = item.url; //完整路径
this.getBlob(url).then(blob => {
this.saveAs(blob, item.fileName);
});
},
getBlob: function(url, cb) {
return new Promise(resolve => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = () => {
if (xhr.status === 200) {
resolve(xhr.response);
}
};
xhr.send();
});
},
saveAs: function(blob, filename) {
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, filename);//允许用户在客户端上保存文件
} else {
const link = document.createElement("a");
const body = document.querySelector("body");
link.href = window.URL.createObjectURL(blob);
link.download = filename;
link.style.display = "none";
body.appendChild(link);
link.click();
body.removeChild(link);
window.URL.revokeObjectURL(link.href);
}
},