a标签的download属性可以对文件进行重命名,但是最近发现了一种情况:下载附件文件时候,由于文件与项目不在同一个域名下,所以出现了a.download属性失效的问题。
跨域时为什么a.download属性会失效?
浏览器获取不到文件,无法进行更改。
实现过程
后端返回的是一个下载链接,但是由于跨域a.download失效,就获取文件的blob之后再进行重命名。
// 下载附件简历
downLoadResume(file, name, id) {
const params = { fileName: file, id: id };
getResueme(params).then((res) => {
const objectUrl = res.data;
const fileName = this.item.name + '_' + this.item.jobName;
var x = new XMLHttpRequest();
x.open('GET', objectUrl, true);
x.responseType = 'blob';
x.onload = function(e) {
//会创建一个 DOMString,其中包含一个表示参数中给出的对象的URL。这个 URL 的生命周期和创建它的窗口中的 document 绑定。这个新的URL 对象表示指定的 File 对象或 Blob 对象。
var url = window.URL.createObjectURL(x.response);
console.log(url);
var a = document.createElement('a');
a.href = url;
a.download = fileName;
a.click();
a.remove();
};
x.send();
}).catch((err) => {
console.log(err);
this.remarkLoading = false;
});
},
|