前端预览pdf文件流

需求

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

解决方案

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

具体实现步骤

1、引入axios

javascript 复制代码
import axios from 'axios';

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

javascript 复制代码
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方法

javascript 复制代码
import { previewFile } from "@/utils";
<el-button type="primary" @click="previewFile(file)">导出已选</el-button>
相关推荐
Mh8 小时前
别再只会 `find` 了:Map 在前端业务里的真实用法
前端·javascript
陈随易9 小时前
FFmpeg 9.0 发布,代号 Lei,音视频处理再升级
前端·后端·程序员
爱丶狸9 小时前
Grafana_Zabbix_ImageRenderer_部署与前端操作手册
linux·前端·zabbix·grafana·kylin
用户0595401744612 小时前
把AI对话记忆存储测试从手工改成Playwright+pytest,覆盖率从20%提到96%,回归时间缩短90%
前端·css
kyriewen12 小时前
别再这样写TypeScript了——Code Review中最常见的8个反模式
前端·javascript·typescript
名字还没想好☜12 小时前
Next.js ‘use client‘ 到底加在哪:Server/Client Components 边界与常见报错
开发语言·前端·javascript·react·next.js
午安~婉13 小时前
GitHub Token/ GitHub Stats统计显示图异常
前端·github·vercel·github token
码云之上13 小时前
AI Agent 工程化总览篇:从 Prompt 到 Harness
前端·人工智能
2501_9269783313 小时前
以说明书 DNA 为模板——完整 AGI 的结构图景
前端·人工智能·经验分享·笔记·ai写作
IT_陈寒13 小时前
Vite静态资源引用这个坑我踩得有点疼
前端·人工智能·后端