文件流导出文件

javascript 复制代码
// 下载excel
export const downloadFile = (fileStream, fileName) => {
  if (window.navigator.msSaveBlob) {
    try {
      window.navigator.msSaveBlob(fileStream, fileName);
    } catch (e) {
      console.log(e);
    }
  } else {
    const url = window.URL || window.webkitURL;
    const bUrl = url.createObjectURL(fileStream);
    let a = document.createElement("a");
    a.style.display = "none";
    a.href = bUrl;
    a.download = decodeURIComponent(fileName);
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    url.revokeObjectURL(bUrl);
  }
};

使用downloadFile(res, `默认文件.xlsx`);

res是后端返回文件流,默认文件.xlsx是文件名 .xlsx是后缀名

javascript 复制代码
// 获取文件类型
export function getFileType(file) {
  const type = file.type || "";
  const name = file.name || "";
  if (type.includes("word")) {
    return "doc";
  } else if (type.includes("excel") || type.includes("spreadsheetml.sheet")) {
    return "excel";
  } else if (type === "text/plain") {
    return "txt";
  } else if (type === "application/pdf") {
    return "pdf";
  } else if (type === "text/html") {
    return "html";
  } else if (type === "text/markdown" || name.includes(".md")) {
    return "md";
  } else {
    return "other";
  }
}
相关推荐
opbr17 分钟前
🚀 告别传统枚举的痛点!TypeScript 中的 constructEnum 让你的代码更优雅 ✨
前端·javascript
鬼鬼_静若为竹18 分钟前
今天在增加了攻击小马的功能
前端
遂心_19 分钟前
React性能优化实战:掌握memo、useCallback与useMemo的精妙用法
前端·javascript·react.js
CodePlayer20 分钟前
《学会提问》读后感
前端·程序员
是晓晓吖21 分钟前
源网站数据采集方案之解析DOM(五)
前端
FogLetter22 分钟前
CSS模块化:告别样式冲突,拥抱组件化开发
前端·react.js
angelQ22 分钟前
针对"@antfu/eslint-config": "^4.17.0"最新版本使用报错Unexpected token 'with'的解决方法
前端·eslint
小飞机噗噗噗22 分钟前
记录js使用原生 XMLHttpRequest方法 封装http请求,并提供使用实例
前端·javascript·react.js
用户25191624271124 分钟前
Canvas之绘制图形后续
前端·javascript·canvas
CodePlayer30 分钟前
《有限与无限的游戏》——读后感
前端·稀土