Blob流数据下载

比较简单,直接上代码

方法一:接口返回型

    // 创建blob对象,解析流数据
    const blob = new Blob([res], {//res为接口返回数据流
      // 设置返回的文件类型
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    });
    //下载方法
    const a = document.createElement("a"); // 创建a标签,模拟点击事件
    const URL = window.URL || window.webkitURL; // 兼容webkix浏览器,处理webkit浏览器中href自动添加blob前缀,默认在浏览器打开而不是下载
    const herf = URL.createObjectURL(blob); // 创建URL 对象
    a.href = herf; // 下载链接
    a.download = "示例"; // 下载文件名;若后端没有返回,可以自己写'文件.xlsx'
    document.body.appendChild(a);
    a.click(); // 点击a标签下载
    document.body.removeChild(a); // 移除URL 对象
    window.URL.revokeObjectURL(herf);

方法二:URL链接型

  const x = new XMLHttpRequest();
  x.open("GET", url, true);//url文件地址,必须填写
  x.responseType = "blob";
  x.onload = e => {
    // 会创建一个 DOMString,其中包含一个表示参数中给出的对象的URL。这个 URL 的生命周期和创建它的窗口中的 document 绑定。这个新的URL 对象表示指定的 File 对象或 Blob 对象。
    const urlF = window.URL.createObjectURL(x.response);
    const a = document.createElement("a");
    a.href = urlF;
    a.download = `${name}`;//name文件名,没有就自己定义
    a.click();
  };
  x.send();

 常见的文件类型大观:

application/msword    //word(.doc)
application/vnd.ms-powerpoint    //powerpoint(.ppt)
application/vnd.ms-excel   //excel(.xls)
application/vnd.openxmlformats-officedocument.wordprocessingml.document    //word(.docx)
application/vnd.openxmlformats-officedocument.presentationml.presentation    //powerpoint(.pptx)
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet    //excel(.xlsx)
application/x-rar-compressed    //rar
application/zip    //zip
application/pdf    //pdf
video/*   // 视频文件
image/*   //图片文件
text/plain    //纯文本
text/css    //css文件
text/html   //html文件
text/x-java-source    //java源代码
text/x-csrc    //c源代码
text/x-c++src    //c++源代码

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值