处理Blob打印Excel

一、 说明

当后端返回Blob二进制文件流,前端根据返回内容生成对应文件,生成a标签,利用a标签的下载特性来完成打印文件的下载。

二、 使用示例

// 引入封装请求方法
import request from 'utils/request';
const downloadDll = async (record) => {
    
    
    const res = await request(`/exportUrl`, {
    
    
      method: 'POST',
      responseType: 'blob',
      body: "请求参数"
    });
    if (res) {
    
    
       const file = new Blob([res], {
    
     type: 'application/vnd.ms-excel' }); // 解析文件
        const fileURL = URL.createObjectURL(file); // 生成文件地址
        const fileName = '文件名称.xls';
        const elink = document.createElement('a'); // 生成a标签
        elink.download = fileName; // a标签下载名
        elink.style.display = 'none'; // 设置a标签隐藏,不在页面展示
        elink.href = fileURL; // 设置a标签下载地址
        document.body.appendChild(elink); // 在body中添加a标签
        elink.click();  // 手动调用a标签点击下载属性
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink); // 在body中删除a标签
    }
  };

三、 注意

  • 请求的返回类型为responseType: blob
  • 实例化Blob时传第二个参数解析文件类型{ type: 'application/vnd.ms-excel' }

四、 补充:下载PDF

const file = new Blob([result], {
    
     
	type: 'application/pdf' }); // 解析文件
const fileURL = URL.createObjectURL(file);  // 创建pdf文件
const newwindow = window.open(fileURL, 'newwindow');  // 打开新的页面进行预览
newwindow ? newwindow.print() : notification.error(
{
    
     message: '当前窗口已被浏览器拦截,请手动设置浏览器!' }); // 判断是否成功打开

猜你喜欢

转载自blog.csdn.net/IO14122/article/details/126361631
今日推荐