工具tool:下载工具函数

124 阅读1分钟

方法1:

步骤:

  • 数据转换为blob对象
  • blob对象通过window.URL.createObjectURL 转换成url
  • 新建a 元素
  • 指定a 元素的href属性为上步骤的url地址,设置属性target 为blank, 设置download属性为制定的文件名
  • 判断是否支持MouseEvent,如果支持,设置click点击事件,并让a元素触发该点击事件

代码如下:

import { message } from "ant-design-vue";

export default (data: any, fileName: string, successText: string) => {
  const linkElement = document.createElement("a");
  const blob = new Blob([data]);
  const hrefUrl = window.URL.createObjectURL(blob);
  linkElement.setAttribute("href", hrefUrl);
  linkElement.setAttribute("target", "_blank");
  linkElement.setAttribute("download", fileName);
  if (typeof MouseEvent === "function") {
    var event = new MouseEvent("click", {
      view: window,
      bubbles: true,
      cancelable: false,
    });
    linkElement.dispatchEvent(event);
    message.success(successText)
  }
}

方法2

  • 数据转换为blob对象
  • blob对象通过window.URL.createObjectURL 转换成url
  • window.open(该url)
const ab = new ArrayBuffer(32)
const iA = new Int8Array(ab)
iA[0] = 97;//把二进制的数据的首位改为97 ,97为小写字母a的ascll码;
const  blob = new Blob([iA], {type: "application/octet-binary"});//把二进制的码转化为blob类型
const url = URL.createObjectURL(blob);
window.open(url)