js download file and front-end use a tag to download file download attribute failure problem

Usually downloaded to create a virtual a tag through document.createElement

  function downloadFileUrl(val, url, fileName) {
      if (isVal) return false;
      let url= `${process.env.BASE_URL}/${url}`;
      const elink = document.createElement('a');
      elink.href = url;
      elink.target = '_self'; // 当前也 target打开新页面
      // elink.setAttribute('download', fileName);
      let name = fileName ? val.split('"')[1] : '输出结果';
      elink.download = `${name}-${fileName}`;  //自定义文件名
      elink.style.display = 'none';
      document.body.appendChild(elink);
      message.success(`${val} ${fileName} 下载成功`);
      setTimeout(() => {
        elink.click();   //模拟出发a 点击事件
        document.body.removeChild(elink); // 删除a
      }, 66);
  }

When using the a tag to download files, the download attribute can change the downloaded file name, but when the download link of the a tag crosses domains, the download attribute will not take effect because the browser cannot obtain the file and cannot change it

Note: The new feature of html5, the download attribute of a tag, only supports Google and Firefox.
In Google and Firefox browsers, the download attribute of a tag can modify the file name.

Solution:
Use HTML5 Blob to realize file download, first download the file to the current page in the form of bobl, and then create a tag.

  function downloadFileUrl(val, url, fileName) { // val是标题 、url 是地址、fileName区分批量还是单个下载参数
    if (isVal) return false;
    let aUrl = `${process.env.BASE_URL}/${url}`;
    const x = new XMLHttpRequest();
    x.open('GET', aUrl, true);
    x.responseType = 'blob';
    x.onload = function (e) {
      const url = window.URL.createObjectURL(x.response);
      const elink = document.createElement('a');
      elink.href = url;
      elink.target = '_self'; // 当前也 target打开新页面
      // elink.setAttribute('download', fileName);
      let name = fileName ? val.split('"')[1] : '输出结果';  //此处根据自己的情况修改
      elink.download = `${name}-${fileName}`;
      elink.style.display = 'none';
      document.body.appendChild(elink);
      message.success(`${val} ${fileName} 下载成功`);
      setTimeout(() => {
        elink.click();
        document.body.removeChild(elink);
      }, 66);
    };
    x.send();
  }

 

 

Guess you like

Origin blog.csdn.net/weixin_46600931/article/details/126854016#comments_26913364