关于Vue中a标签下载的文件重命名处理办法。

用默认的a标签下载:

var link = document.createElement('a');
link.href = file.url;
link.download = file.name;
link.target="_blank";
link.click();

但此方法仅在不跨域的情况下可用。

跨域的情况下则可用如下办法:

1.点击下载按钮调用

  dfLoad(file) {
      this.getBlob(file.url).then(blob => {
         this.DownloadItem(blob, file.fileName);
     });
   },

2.通过传入的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();
  });
},

3.最后调用下载文件的方法

  DownloadItem(blob,fileName){
         let link = document.createElement('a');
         link.href = window.URL.createObjectURL(blob);
         link.download = fileName;
         link.click();
    },

原文:https://blog.csdn.net/pqj222/article/details/102628834?spm=1001.2101.3001.6650.3&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-3.pc_relevant_aa&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-3.pc_relevant_aa&utm_relevant_index=5

posted @ 2022-02-21 17:23  清风园  阅读(2508)  评论(0编辑  收藏  举报