前端文件下载多方式集合

基于vue+element UI框架

javascript 复制代码
// @ts-ignore
import axios from "axios";
import { ElMessage } from "element-plus";
import webConfig from "@/config";

class FileDownload {
  /**
   * 文件流下载
   *  @param url string 下载地址
   *  @param params object 请求参数
   *  @param fileName string 文件名
   * @param method
   */
  // eslint-disable-next-line @typescript-eslint/ban-types
  static streamDownLoad(url: string, params: object, fileName: string, method = "GET"): void {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    return axios({
      url: url,
      params,
      data: params,
      method,
      headers: {
        "X-Access-Token": window.lxLocalStorage.getItem("token"),
        token: window.lxLocalStorage.getItem("token"),
      },
      responseType: "blob",
    })
      .then(async (res: { data: any }) => {
        console.log(res);
        // @ts-ignore
        const contentDispositio = res.headers["content-disposition"];
        if (contentDispositio) {
          const f = contentDispositio.match(/filename=.+/gi, "$0");
          if (f && f.length) {
            fileName = window.decodeURI(f[0].replace(/filename=/gi, ""));
          }
        }
        const fileBlob = res.data;
        const fileType = fileBlob.type;
        if (fileType === "application/json") {
          const text = await fileBlob.text();
          const jsonText = JSON.parse(text);
          // @ts-ignore
          ElMessage.error(`文件下载失败:${jsonText?.message}`);
        } else if (fileBlob instanceof Blob) {
          const blob = new Blob([fileBlob]);
          const downloadElement = document.createElement("a");
          const href = window.URL.createObjectURL(blob);
          downloadElement.href = href;
          downloadElement.download = fileName;
          document.body.appendChild(downloadElement);
          downloadElement.click();
          document.body.removeChild(downloadElement);
          window.URL.revokeObjectURL(href);
        }
      })
      .catch((err: Error) => {
        // @ts-ignore
        ElMessage.error(`文件下载失败:${err.message}`);
      });
  }

  /**
   * 直接通过 a 标签下载文件 最好不要用这种方式 缺少一定的安全验证
   */
  static aDownLoad(url: string, fileName: string): void {
    const link = document.createElement("a");
    link.style.display = "none";
    link.href = `${webConfig.fileServer}/file/file/download?url=${url}&fileName=${fileName}`;
    link.download = fileName || "无标题文件";
    link.setAttribute("target", "_blank");
    link.click();
    link.remove();
  }
  /**
   * base64下载
   */
  static base64DownLoad(content: string, fileName: string, suffix: string): void {
    const DOWNLOAD_TYPE_MAP: any = {
      xls: "application/vnd.ms-excel",
      xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      doc: "application/msword",
      docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      pdf: "application/pdf",
    };
    const prefix = "data:" + DOWNLOAD_TYPE_MAP[suffix] + ";base64,";
    const url = prefix + content;
    const name = `${fileName}.${suffix}`;
    const link = document.createElement("a");
    link.style.display = "none";
    link.href = url;
    link.setAttribute("download", name);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }

  /**
   * 导出文件
   * @param api
   * @param params
   */
  static exportFile(api: string, params?: any) {
    let api_url = api;
    if (params) {
      api_url = `${api_url}?${Object.keys(params)
        .map(k => k + "=" + encodeURIComponent(params[k] != null ? params[k] : ""))
        .join("&")}`;
    }
    console.log(api_url);
    window.open(api_url);
  }
}

export default FileDownload;

技术交流+V: bloxed

相关推荐
AI大模型顾潇13 分钟前
[特殊字符] 本地大模型编程实战(29):用大语言模型LLM查询图数据库NEO4J(2)
前端·数据库·人工智能·语言模型·自然语言处理·prompt·neo4j
九月TTS35 分钟前
TTS-Web-Vue系列:Vue3实现内嵌iframe文档显示功能
前端·javascript·vue.js
爱编程的小学究36 分钟前
【node】如何把包发布到npm上
前端·npm·node.js
weixin_473894771 小时前
前端服务器部署分类总结
前端·网络·性能优化
LuckyLay1 小时前
React百日学习计划-Grok3
前端·学习·react.js
澄江静如练_1 小时前
小程序 存存上下滑动的页面
前端·javascript·vue.js
互联网搬砖老肖2 小时前
Web 架构之会话保持深度解析
前端·架构
菜鸟una2 小时前
【taro3 + vue3 + webpack4】在微信小程序中的请求封装及使用
前端·vue.js·微信小程序·小程序·typescript·taro
hao_04132 小时前
elpis-core: 基于 Koa 实现 web 服务引擎架构设计解析
前端
狂野小青年3 小时前
npm 报错 gyp verb `which` failed Error: not found: python2 解决方案
前端·npm·node.js