封装一个简单的文件下载 js 并且直接获取 文件名

39 阅读1分钟

// FileDownloadUtils.js

function getFileName(disposition) {
  const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
  const matches = filenameRegex.exec(disposition);
  const rawFilename = matches && matches[1] ? matches[1].replace(/['"]/g, '') : 'file.txt';
  // 解码中文字符
  const decodedFilename = decodeURIComponent(rawFilename);
  return decodedFilename;
}

function createAndDispatchDownloadLink(blobUrl, filename) {
  const a = document.createElement('a');
  a.href = blobUrl;
  a.download = filename;
  const evt = document.createEvent('MouseEvents');
  evt.initEvent('click', true, true);
  a.dispatchEvent(evt);
  URL.revokeObjectURL(blobUrl);
}

export function downloadFile(response) {
  const disposition = response.headers['content-disposition'];
  const filename = getFileName(disposition);

  if ('msSaveOrOpenBlob' in window.navigator) {
    // 兼容IE
    window.navigator.msSaveOrOpenBlob(response.data, filename);
    return;
  }

  const blobUrl = URL.createObjectURL(response.data);
  createAndDispatchDownloadLink(blobUrl, filename);
}