前端实现自定义下载文件的名称

2,028 阅读1分钟

今天分享一个小技术点,最近接触的项目中,有个需求是通过前端重新给文件命名,因为我们的文件是存放再fastdfs里面的,所有文件名是Hash值,所以需要前端重新命名文件。

一般有2种方式

  • 1.修改响应中的 Response.AppendHeader("Content-Disposition","attachment;filename=FileName.txt");
  • 2.第二种就是前端请求arraybuffer再自定义文件名

这里采取第二种,代码如下

const fileName = '重新命名的文件名.docx';
const xhr = new XMLHttpRequest();
xhr.open('GET', './test.docx', true);

xhr.responseType = 'arraybuffer';
xhr.onload = function () {
  if (this.status === 200) {
    let type = xhr.getResponseHeader('Content-Type');

    let blob = new Blob([this.response], { type: type });

    // NOTE  有名字的下載和無名字的下載
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
      /*
       * IE workaround for "HTML7007: One or more blob URLs were revoked by closing
       * the blob for which they were created. These URLs will no longer resolve as
       * the data backing the URL has been freed."
       */
      window.navigator.msSaveBlob(blob, fileName);
    } else {
      let URL = window.URL || window.webkitURL;
      let objectUrl = URL.createObjectURL(blob);
      if (fileName) {
        var a = document.createElement('a');
        // safari doesn't support this yet
        if (typeof a.download === 'undefined') {
          window.location = objectUrl;
        } else {
          a.href = objectUrl;
          a.download = fileName;
          document.body.appendChild(a);
          a.click();
          a.remove();
        }
      } else {
        window.location = objectUrl;
      }
    }
  }
};
xhr.send();