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');
 });

本文标签: 对其重命名完整标签方式