关于前端的文件下载问题,通过超链接a无法自定义文件名

1.我们下载文件可以通过创建超链接a的形式,也可以通过文件流的方式。

 downloadFile(sourceUrl,fileName) {
      const link = document.createElement('a');
      link.style.display = 'none';
      // 设置下载地址
      link.setAttribute('href', sourceUrl);
      // 设置文件名
      link.setAttribute('download', fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
}

2.上述方式下载文件无法命名文件,改成一下方式就可以。

    downloadFile(sourceUrl,fileName) {
      const xhr = new XMLHttpRequest();
      xhr.open('GET', sourceUrl, true);
      xhr.responseType = 'blob';
      xhr.onload = function () {
        if (xhr.status === 200) {
          const res = xhr.response;
          const link = document.createElement('a');
          link.style.display = 'none';
          const url = window.URL.createObjectURL(res);
          link.href = url;
          link.setAttribute('download', fileName);
          document.body.appendChild(link);
          link.click();
          window.URL.revokeObjectURL(link.href);
          document.body.removeChild(link);
        }
      }
      xhr.send()
    },

猜你喜欢

转载自blog.csdn.net/qq_44890362/article/details/133081176