预览 PDF 文档

news/2025/1/15 22:50:24/

引言

在现代Web应用中,文件预览功能是非常常见的需求之一。特别是在企业级应用中,用户经常需要查看各种类型的文件,如 PDF、Word、Excel 等。本文将详细介绍如何在Vue项目中实现 PDF 文档的预览功能。

实现原理

后端API

后端需要提供一个API接口,用于获取文件的二进制数据。这个接口通常会根据文件名或文件ID来返回文件内容。

html" title=前端>前端处理

html" title=前端>前端通过调用后端 API 获取文件的二进制数据,并将其转换为 Blob 对象。然后使用window.URL.createObjectURL 方法生成一个临时的 URL,最后通过 window.open 方法在新窗口中打开这个 URL,从而实现文件预览

代码示例

node__9">node 服务端代码

javascript">const express = require('express');
const multer = require('multer');
const fs = require('fs');
const path = require('path');const app = express();
// 定义文件夹路径
const mergedDir = path.join(__dirname, 'merged');// 文件下载接口
app.get('/download', (req, res) => {const { fileName } = req.query;const filePath = path.join(mergedDir, fileName);fs.access(filePath, fs.constants.F_OK, (err) => {if (err) {return res.status(404).json({ error: '文件不存在' });}const stats = fs.statSync(filePath);if (stats.isFile()) {const contentType = getContentType(fileName);res.setHeader('Content-Type', contentType);// 对 fileName 进行编码const encodedFileName = encodeURIComponent(fileName);res.setHeader('Content-Disposition', `attachment; filename=${encodedFileName}`);fs.createReadStream(filePath).pipe(res);} else {res.status(400).json({ error: '不是一个文件' });}});
});// 获取文件的 MIME 类型
function getContentType(fileName) {const ext = path.extname(fileName).toLowerCase();switch (ext) {case '.js':return 'application/javascript';case '.json':return 'application/json';case '.html':return 'text/html';case '.css':return 'text/css';case '.txt':return 'text/plain';case '.png':return 'image/png';case '.jpg':case '.jpeg':return 'image/jpeg';case '.gif':return 'image/gif';case '.html" title=pdf>pdf':return 'application/html" title=pdf>pdf';case '.doc':return 'application/msword';case '.docx':return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';case '.ppt':return 'application/vnd.ms-powerpoint';case '.pptx':return 'application/vnd.openxmlformats-officedocument.presentationml.presentation';case '.xlsx':return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';default:return 'application/octet-stream';}
}
// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {console.log(`Server is running on port ${PORT}`);
});

html" title=前端>前端代码实现

接口 API

javascript">import request from "@/utils/request";// 获取文件列表
export function getFilesList() {return request({url: "/getFilesList",method: "get",});
}// 文件预览
export function previewFile(fileName) {return request({url: `/download?fileName=${fileName}`,method: "get",responseType: "blob",});
}

页面代码

javascript"><template><div class="table"><el-table :data="tableData" header-align="center" border style="width: 100%"><el-table-column align="center" type="index" width="60" label="序号"></el-table-column><el-table-column align="center" prop="fileName" label="文件名" /><el-table-column align="center" prop="upTime" label="上传日期" width="200" /><el-table-column align="center" fixed="right" label="操作" width="120"><template slot-scope="scope"><el-button @click="handleClick(scope.row)" type="text">预览</el-button></template></el-table-column></el-table></div>
</template><script>
import { previewFile } from "@/api/file";
import { timeStampToString } from "@/utils/utils";
import { getFilesList } from "@/api/file";export default {name: "fileTable",data() {return {tableData: [],}},created() {this.getFileName();},methods: {// 获取文件列表async getFileName() {const { code, data: resData } = await getFilesList();console.log('code, data::: ', code, resData);if (code === 200) {resData.forEach(item => {item.upTime = timeStampToString(item.upTime);});this.tableData = resData;}},handleBlob(blob, filename) {console.log('blob::: ', blob,filename);let url = window.URL.createObjectURL(blob);var tempwindow = window.open("_blank");if (tempwindow) {tempwindow.location = url;}},// 文件预览async handleClick(row) {try {const response = await previewFile(row.fileName)console.log('response::: ', response);this.handleBlob(response, row.fileName)} catch (err) {console.error('Failed to preview file', err);}},}
}
</script>

实现效果
在这里插入图片描述

设置网页标题为文件名

javascript"> handleBlob(blob, filename) {console.log('blob::: ', blob, filename);let url = window.URL.createObjectURL(blob);// 创建一个新窗口let tempWindow = window.open("", "_blank");// 设置新窗口的标题为文件名tempWindow.document.title = filename;// 在新窗口中嵌入一个 <iframe> 来预览 PDF 文件tempWindow.document.write('<html><head><title>' + filename + '</title></head><body>');tempWindow.document.write('<iframe src="' + url + '" style="width:100%;height:100%;border:none;"></iframe>');tempWindow.document.write('</body></html>');// 确保新窗口的内容加载完成后再释放 URLtempWindow.onload = function () {window.URL.revokeObjectURL(url);};},

修改后的效果
在这里插入图片描述

在线预览 Word 文档:https://blog.csdn.net/a123456234/article/details/143427145

总结

本文详细介绍了如何在Vue项目中实现PDF文档的预览功能。通过前后端的协同工作,我们实现了从文件的存储、获取到预览的完整流程。具体来说:

  • 后端API:提供了文件下载接口,根据文件名或文件ID返回文件的二进制数据,并设置了正确的MIME类型。

  • html" title=前端>前端处理:通过调用后端API获取文件的二进制数据,将其转换为 Blob 对象,并生成一个临时的 URL。然后在新窗口中打开这个 URL,实现文件预览

  • 优化体验:为了提升用户体验,我们进一步优化了预览功能,通过在新窗口中嵌入 <iframe> 并设置网页标题为文件名,使得预览界面更加友好和直观。

通过本文的介绍,读者可以轻松地在自己的Vue项目中实现类似的功能,提升应用的用户体验。希望本文对大家有所帮助。


http://www.ppmy.cn/news/1544347.html

相关文章

el-select、el-autocomplete的选项内容过长显示完整内容

问题&#xff1a; el-select、el-autocomplete的选项内容过长需要看清完整内容 解决方案&#xff1a; 使用el-popover悬停显示完整内容 代码&#xff1a; <el-form-item label"备注" prop"remark"><el-autocomplete v-model"form.remar…

php实现sl651水文规约解析

SL651-2014-《水文监测数据通信规约》 1、要素解析说明 39 23 00 00 03 45 0x39查标识符得知为:39H Z 瞬时河道水位、潮位,我们定义为水位 0x23 按照要素标识符的规定,高5bit,低3bit,00100 011 对应的转换为10进制为4与3,也就是水位数据占用4字节,小…

Cocos使用精灵组件显示相机内容

Cocos使用精灵组件显示相机内容 1. 为什么使用精灵渲染 在游戏引擎中&#xff0c;游戏场景内除webview和video外所有的节点都是渲染在Canvas上&#xff0c;这导致了webview和video只能存在于所有节点的最上层或最下层&#xff0c;而这种层级关系会出现节点事件无法正常监听或者…

【1】Excel快速入门的核心概念

1. 工作表 基本工作表 图表工作表 工作表视图 2.表格(Table)&#xff0c;套用表格格式 ​ 名称&#xff08;表&#xff0c;列&#xff09; ​ 结构化引用[列名] ​ 设置表格样式 -可自定义&#xff08;如报表类&#xff09; ​ 数据验证 -交互 &#xff08;输入/输出交…

MATLAB/Simulink学习|在Simulink中调用C语言-04使用C Function 实现PI运算(使用模块自定义代码-仿真自定义代码)

在上一篇博客中&#xff0c;介绍了如何使用C Function 实现PI运算&#xff0c;但是在模块内编辑C代码&#xff0c;而不能直接调用已经写好了的C代码。 在Simulink中使用C Function调用自定义代码有两种方法&#xff0c;本篇博客介绍其中一种方法。 添加头文件和源文件 在实际…

P10424 [蓝桥杯 2024 省 B] 好数 题解

题目名字 P10424 [蓝桥杯 2024 省 B] 好数 题解 题目链接 题意 给一个整数n&#xff0c;从1到n这个区间范围内&#xff0c;每一个数位为偶数的数字为偶数且数位为奇数的数字为奇数&#xff0c;那么这个数就是好数 思路 首先确认所有的条件都必须要满足&#xff0c;奇对奇&…

ubuntu20安装opencv3.2记录

系统环境 ubuntu20安装了ros-noetic&#xff0c;所以系统默认装了opencv4.2.0&#xff0c;但是跑fastlivo推荐的是opencv3.2.0&#xff0c;而且海康相机别人写的ros驱动&#xff08;海康相机ros驱动&#xff09;也是需要opencv3.2.0&#xff0c;最终还是选择安装多版本的openc…

第三十章 章节练习商品列表组件封装

目录 一、需求说明 二、技术要点 三、完整代码 3.1. main.js 3.2. App.vue 3.3. MyTable.vue 3.4. MyTag.vue 一、需求说明 1. my-tag 标签组件封装 (1) 双击显示输入框&#xff0c;输入框获取焦点 (2) 失去焦点&#xff0c;隐藏输入框 (3) 回显标签信息 (4) 内…