前端预览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>
相关推荐
名字还没想好☜几秒前
Next.js 用 cookies()/headers() 读请求信息:动态渲染触发、缓存失效与在 Server Action 里读写 cookie
前端·javascript·缓存·react·next.js·app router
今日无bug18 分钟前
从「拿来主义」到「亲手造轮子」:2 种 MCP 文件服务器写法对比
前端·node.js·mcp
xcyxiner19 分钟前
flutter 运行到模拟器上
android·前端·flutter
用户9210802628619 分钟前
从 COT 到 ThoughtChain:AI 应用为什么需要展示“思考过程”
前端
天真小巫20 分钟前
2026.8.23总结
前端·html
PedroQue9920 分钟前
RouterLink v2.5.0:H5端原生能力全面回归
前端·uni-app
八角丶23 分钟前
Node.js 异步上下文详解(实验驱动)
前端·node.js
用户21816970493025 分钟前
Flutter (二十五)视频播放
前端
半个落月26 分钟前
在浏览器里运行 DeepSeek-R1:推理、流式输出与停止生成(二)
前端·人工智能·react.js
绿岛之北27 分钟前
Electron 安全第四章: Preload 与 IPC
前端·electron