js/axios/umi-request 根据后端返回的二进制流下载文件

javascript 复制代码
type ResponseType = {
  data: Blob;
  headers: {
    'content-disposition'?: string;
  };
};
// 下载 (创建a标签)
export const downloadBlob = (response: ResponseType) => {
  const blob = response.data; // 获取响应中的 Blob 数据
  const contentDisposition = response.headers['content-disposition'];
  let fileName = ''; // 默认文件名
  if (contentDisposition) {
    // 提取文件名并解码成中文
    const fileNameRegex = /filename=([^;]+)/;
    const fileNameMatch = contentDisposition.match(fileNameRegex);
    fileName = fileNameMatch ? fileNameMatch[1] : '';
    if (fileName) {
      fileName = decodeURIComponent(fileName);
    }
  }
  // 创建 Blob 对象后,你可以根据需要执行文件下载逻辑
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = fileName; // 设置下载文件的名称
  link.style.display = 'none';
  document.body.appendChild(link);
  link.click();
  // 清除创建的链接
  window.URL.revokeObjectURL(url);
  document.body.removeChild(link);
};

用法很简单。

javascript 复制代码
  const downLoad= async () => {
    const response = await axios(...);
    //将完整的响应头丢进去即可
    aDownload(response);
  };
相关推荐
彷徨而立几秒前
【C++】 using声明 与 using指示
开发语言·c++
前端小张同学6 分钟前
前端行情好起来了,但是我依然没拿到offer
前端
程序员小续8 分钟前
React 官方严令禁止:Hook 不能写在 if/else,真相竟然是…
前端·javascript·程序员
懒得不想起名字8 分钟前
flutter_riverpod: ^2.6.1 应用笔记
前端
CrabXin8 分钟前
让网页在 PC 缩放时“纹丝不动”的 4 个技巧
前端·react.js
@半良人16 分钟前
Deepseek+python自动生成禅道测试用例
开发语言·python·测试用例
Juchecar19 分钟前
Naive UI 学习指南 - Vue3 初学者完全教程
前端·vue.js
用户81686947472520 分钟前
从0到1教你开发一个Mini-ESLint
前端·开源
coding随想20 分钟前
JavaScript中的DOM事件对象Event全解析
前端
专研狂21 分钟前
React 的闭包陷阱 + 状态异步更新机制
前端