前端预览pdf文件流

需求

后端接口返回pdf文件流,实现新窗口预览pdf。

解决方案

把后端返回的pdf文件流转为blob路径,利用浏览器直接预览。

具体实现步骤

1、引入axios

复制代码
import axios from 'axios';

2、创建预览方法(具体使用时将axios的请求路径替换为你的后端下载地址)

复制代码
export async function previewFile(data: IAttachment, callback?: () => void) {
  try {
    const response = await axios.get(config.VITE_APP_API_URL_PREPROD + '/file/downloadFile', {
      params: {
        filepath: data.filePath
      },
      responseType: 'blob'
    });
    let pdfUrl = window.URL.createObjectURL(new Blob([response.data], { type: "application/pdf" }));
    window.open(pdfUrl, "_blank");
    const newWindow = window.open(pdfUrl, '_blank');
      if (newWindow) {
        newWindow.onload = () => {
          newWindow.focus();
        };
      } else {
        // 如果新窗口被阻止,提示用户
        ElMessage.warning($t('请允许弹出窗口以预览文件'));
      }
  } catch (error) {
    console.error('Error preview file:', error);
  }
}

3、在你所需要的地方调用previewFile方法

复制代码
import { previewFile } from "@/utils";
<el-button type="primary" @click="previewFile(file)">导出已选</el-button>
相关推荐
倾颜6 小时前
从 textarea 到 AI 输入框:用 Tiptap 实现 / 命令、@ 引用和结构化请求
前端·langchain·next.js
kyriewen7 小时前
程序员连夜带团队跑路,省了23万:这AI太贵,真的用不起了
前端·javascript·openai
kyriewen8 小时前
你写的代码没有测试,就像出门不锁门——Jest + Testing Library 从入门到不慌
前端·单元测试·jest
yuzhiboyouye8 小时前
web前端英语面试
前端·面试·状态模式
:mnong9 小时前
附图报价系统设计分析5
electron·pdf·vue·cad·dwg·定额
canonical_entropy10 小时前
下一代低代码渲染框架 nop-chaos-flux 的设计原则
前端·低代码·前端框架
东方小月10 小时前
5分钟搞懂Harness Engineering(驾驭工程):从提示词到AI Agent的进化之路
前端·后端·架构
我叫黑大帅10 小时前
为什么需要 @types/react?解决“无法找到模块 react 的声明文件”报错
前端·javascript·面试
之歆10 小时前
DAY_21JavaScript 深度解析:数组(Array)与函数(Function)(一)
前端·javascript
XinZong11 小时前
【AI社交】基于OpenClaw自研轻量化AI社交平台实战
前端