一、正常情况下,我们都如此下载文件并修改文件名,在a标签上面添加download属性
var link = document.createElement('a'); link.href = file.url; link.download = file.name; //link.target="_blank"; link.click();
由于a.download跨域会失效,上面代码只可同域实现
二、通过blob实现跨域下载并修改文件名(同样适用于URL地址)
//通过文件下载url拿到对应的blob对象
getBlob(url) { 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(); });
js模拟点击a标签进行下载
//下载文件 saveAs(blob, filename) { var link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.download = filename; link.click(); }
调用(name 要携带后缀名)
this.getBlob(file.url).then(blob => { this.saveAs(blob,'文件名.docx'); });