前端下载文件

🌺 摘要
前端下载文件

/**
 * 接收后端文件流并下载 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);
}