前端预览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>
相关推荐
欣欣之王来了1 小时前
原始HTML插值:v-html指令的使用与安全风险
前端·学习·架构·项目·vue3教程
IT_陈寒1 小时前
Redis的LRU淘汰策略坑了我一整天
前端·人工智能·后端
计算机魔术师1 小时前
砍半价格、参数再涨,国产旗舰追到 Opus 鼻尖了
前端
特立独行的猫A1 小时前
10 MB 的桌面 AI 客户端:用仓颉 + 系统 WebView 替代 Electron
前端·harmonyos
修炼的dance2 小时前
白底图存JPG,sharp开mozjpeg背景杂点少近三成
前端
anOnion2 小时前
构建无障碍组件之Grid Pattern
前端·html·交互设计
乔旭伟3 小时前
Vben3 中后台表格封装实战:useVbenVxeGrid 的全局收敛与七个坑
前端·anti-design-vue·1024程序员节
鶴哥只手遮天3 小时前
jQuery 4.0 源码架构与工程实践-第 10 章 尺寸、几何与显隐
前端·javascript·jquery
Mia_墨黎3 小时前
2026 Windows 11 终端美化完全指南
前端·后端
用户1880687493523 小时前
戴着 Rokid 接成语:用 AIUI 做一局有提示、有复盘的“接着说”
前端