前端预览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>
相关推荐
子兮曰2 小时前
PHP漏洞危机,你的网站升级了吗?
前端·后端·php
jerrywus2 小时前
给 Pi 装上生图插件:从登录报错到画出一只 200×200 的猫
前端·agent·claude
陈随易2 小时前
搞钱点子之生态鱼缸
前端·后端·程序员
PBitW2 小时前
从空目录到上线:我全程用 TRAE 做了一款微信小游戏合集(含一次完整架构重构)
前端·trae
不爱学英文的码字机器2 小时前
从Q1迁到T1,同一个编号已经换了含义
前端·数据库·microsoft
云和数据.ChenGuang2 小时前
光哥说Python 循环导入(Circular Import)深度解析:成因、排查与解决方案
开发语言·前端·人工智能·python·langchain
avi91112 小时前
【AI教人】在Inspector显示所有Delegate-Odin Inspector之三
java·前端·算法·delegate·inspector·editor扩展·unity editor
fengci.2 小时前
BUUCTF(困难部分)
android·开发语言·前端·学习·php
Ward的AI产品实战2 小时前
开源 AI 网关 Magpie 调优终结篇:顺位排错、跨家族对抗审查与 5 大路由组重构(下篇)
前端·人工智能
Highcharts.js2 小时前
BI可视化图表“维护难”问题的解决方案
开发语言·前端·javascript·编辑器·ecmascript·bi·highcharts