admin管理员组文章数量:1606474
一、正常情况下,我们都如此下载文件并修改文件名,在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');
});
版权声明:本文标题:js通过a标签的方式下载文件并对其重命名的完整方案 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dianzi/1728499002a1160971.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论