前端下载文件

徐徐
前端
发表于 2026/04/20 16:00
🌺 摘要
通过 `Blob + URL.createObjectURL + a.download` 实现文件下载,并演示从 `content-disposition` 提取文件名。

/**
 * 接收后端文件流并下载 Excel
 * @param blob 后端返回的 Blob
 * @param defaultFileName 默认文件名
 */
export function downloadFile(
  blob: Blob,
  defaultFileName = "导出文件.xlsx",
): void {
  // 获取文件名(从响应头 content-disposition)
  let fileName = defaultFileName;
  const contentDisposition = (blob as any)?.type
    ? undefined
    : (blob as any)?.$headers?.["content-disposition"];

  if (contentDisposition) {
    const fileNameMatch = contentDisposition.match(
      /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/,
    );
    if (fileNameMatch && fileNameMatch[1]) {
      fileName = decodeURIComponent(fileNameMatch[1].replace(/['"]/g, ""));
    }
  }

  // 创建下载链接
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = fileName;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  window.URL.revokeObjectURL(url);
}
文章发表于 2026/04/20 16:00
作者: 徐徐
文章标题: 前端下载文件
版权声明: 内容遵守许可协议,转载请注明出处。
扫码阅读原文

评论

加载中...