Vue 项目:js 模拟点击 a 标签下载文件并重命名

一、正常情况下,我们都如此下载文件并修改文件名,在a标签上面添加download属性

    //文件下载 由于a.download跨域会失效,代码只可同域实现
    downFile() {
      if ('download' in document.createElement('a')) {
        // 非IE下载
        const elink = document.createElement('a')
        elink.href = imgView + 'group1/M00/00/88/FGQfoGIOD3mAW4ezAABGAM4MtrA503.xls' //file.url
        elink.download = 'xyqzmb.xls' //file.name
        elink.style.display = 'none'
        //link.target="_blank";
        elink.click()
     }

或者是转blob方式:

console.log(data)
var url = data.url;
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);//get请求,请求地址,是否异步
xhr.responseType = "blob";  // 返回类型blob
xhr.onload = function () {// 请求完成处理函数
    if (this.status === 200) {
        var blob = this.response;// 获取返回值
        var a = document.createElement('a');
        a.download = data.name;
        a.href=window.URL.createObjectURL(blob);
        a.click();
    }
};
// 发送ajax请求
xhr.send();

二、通过blob实现跨域下载并修改文件名(同样适用于URL地址)

 <a-button type="primary" icon="download" @click="downFile">下载</a-button>

    //文件下载
    downFile() {
      let fileUrl = imgView + 'group1/M00/00/88/FGQfoGIPDfuAErRaAABGAH4FyJ4422.xls'  //服务器文件地址
      this.getBlob(fileUrl).then(blob => {
        this.saveAs(blob, '信用权证使用导入模板件名.xlsx')
      })
    },
    //通过文件下载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()
    },

原文地址:https://blog.csdn.net/ZiChen_Jiang/article/details/122999731

推荐阅读