前端上传el-upload、原生input本地文件pdf格式(纯前端预览本地文件不走后端接口)

前端实现本地文件上传与预览(PDF格式展示)不走后端接口

实现步骤

第一步:文件选择

使用前端原生input上传本地文件,或者是el-upload组件实现文件选择功能,核心在于文件渲染处理。(input只不过可以自定义样式)

 <div v-if="!uploaded" v-loading="loading" class="upload_box"><p @click="openFileSelector()"><img src="@/assets/上传文件.png" @dragover.prevent @drop.prevent="onDrop" @dragenter.prevent="onDragEnter"@dragleave.prevent="onDragLeave" style="padding-left: 30px" /><input :id="'file' + title" type="file" ref="fileInput" single accept=".pdf" @change="handleFileSelect"style="display: none" /><span class="card_text" for="file">请上传本地文件</span><span class="card_text" style="font-weight: 400">支持选择、拖拽上传PDF</span></p></div>

第二步:文件处理

通过URL.createObjectURL(file)将本地文件转换为URL进行访问。

<script>methods: {//点击上传的方法openFileSelector() {// console.log('aaaa');const filedox = document.getElementById("file" + this.title);filedox.click();//this.fileInputRef.click();},}//拖拽的方法onDrop(event) {// console.log('ondrop',event)this.isDragging = false;const file1 = event.dataTransfer.files[0];this.uploaded = true;this.loading = falseif (file1 && file1.type === 'application/pdf') {//重点是这里将文件转换成本地url地址去访问const blobUrl = URL.createObjectURL(file1);// http://192.168.203.213:8080// console.log('blobUrl',blobUrl)//将url返回给标签渲染的this.pdfPreview = blobUrl}for (let i = 0; i < files.length; i++) {const file = files[i];if (file.type === "application/pdf" ||file.type === "application/msword" ||file.type ==="application/vnd.openxmlformats-officedocument.wordprocessingml.document") {let transform_type_val;if (files[0].type === "application/pdf") {if (this.routerType == 'word') {transform_type_val = 'pdf2word';file.transform_type = transform_type_val;} else if (this.routerType == 'excel') {transform_type_val = 'risk';file.extract_type = transform_type_val;}// console.log('pdf',file.transform_type)}this.selectedFiles.push(file);}}// this.uploadFiles();this.fileInputRef.value = null;},//input事件 和 拖拽事件一致handleFileSelect(event) {const file1 = event.target.files[0];if (file1 && file1.type === 'application/pdf') {this.uploaded = true;this.loading = falseconst blobUrl = URL.createObjectURL(file1);// http://192.168.203.213:8080// console.log('blobUrl',blobUrl)this.pdfPreview = blobUrl} else {this.$message.error('仅支持pdf格式文件');return;}// console.log('触犯上传',files);// for (let i = 0; i < files.length; i++) {// const file = files[i];const file = files[0];const regx = /\.docx$/i;const regc = /\.doc$/i;// console.log('file==',file)if (file.type === "application/pdf" ||file.type === "application/msword" ||file.type === "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||regx.test(file.name) || regc.test(file.name)) {let transform_type_val;if (files[0].type === "application/pdf") {if (this.routerType == 'word') {transform_type_val = 'pdf2word';file.transform_type = transform_type_val;} else if (this.routerType == 'excel') {transform_type_val = 'risk';file.extract_type = transform_type_val;}// console.log('pdf',file.transform_type)}//this.selectedFiles.push(file);// console.log('this.selectedF/iles',this.selectedFiles)}// }// this.uploadFiles();this.fileInputRef.value = null;},//走接口的方法async uploadFiles() {// console.log('this.selecte/dFiles==',this.selectedFiles)if (this.selectedFiles.length === 0) {this.$message.warning("没有选择要上传的文件");return;}const pattern = /http:\/\/oss:/g;// const pattern = /http:\/\/127.0.0.1:/g;const formData = new FormData();let ConvertPDF = false;// console.log('this.selectedFiles===',this.selectedFiles)this.selectedFiles.forEach((file) => {// if(file.transform_type=='pdf2word'){//   ConvertPDF = true// }formData.append("file", file);// console.log('2656251==',)if (this.routerType == 'word') {formData.append("transform_type", file.transform_type);} else if (this.routerType == 'excel') {formData.append("extract_type", file.extract_type);}});// console.log('didiididi==',)const aiToken = sessionStorage.getItem("aiToken");const xtpToken = sessionStorage.getItem("xtpToken");let apiUrlif (this.routerType == 'word') {apiUrl = '/api/v1/transform/create'// apiUrl = '/api/api/v1/transform/create'} else if (this.routerType == 'excel') {apiUrl = '/api/v1/extract/create'// apiUrl = '/api/api/v1/extract/create'}try {// console.log('上传')const response = await axios.post(apiUrl,formData,{headers: {"Content-Type": "multipart/form-data",token: aiToken ? aiToken : xtpToken,},});this.loading = truethis.$message.success("文件上传成功");//这应该获得上传好文件的id// console.log('didi==',response.data.data);let id = response.data.data.id;this.$emit('upload', id)if (!id) {this.$message.warning('请上传文件')return} else {const fileId = idif (this.routerType == 'word') {startTransform({ transform_task_id: fileId }).then((res) => {// console.log('转换',res);})} else if (this.routerType == 'excel') {startExtract({ extract_task_id: fileId }).then((res) => {// console.log('转换',res);}).finally(() => {console.log("无论如何都执行")});}if (this.routerType == 'word') {this.$router.push('/wordTable')} else if (this.routerType == 'excel') {this.$router.push('/excelTable')}}let src = '';let errorMsg = '';// 判断是否转pdf走转pdf的接口if (ConvertPDF) {this.timer = setInterval(() => {detai(id).then((res) => {src = res.data.pdf_filepath;errorMsg = res.data.convert_errorif (src) {const a = src.replace(pattern, `http://10.223.33.105:`);this.ispdf = true;this.pdfsrc = a;this.uploaded = true;this.loading = falseclearInterval(this.timer)}if (errorMsg) {this.$message.error("文件转换失败" + errorMsg);}})}, 3000);} else {//在这获取要展示的pdf地址// file_url// console.log('在这获取要展示的pdf地址',response.data)src = response.data.data.file_url;// const a = src.replace(pattern, `http://192.168.202.231:`);const a = src.replace(pattern, `http://10.223.33.105:`); this.ispdf = true;this.pdfsrc = a;this.uploaded = true;// console.log('pdfsrc==',this.pdfsrc)}} catch (error) {// this.uploaded = true;this.$message.error("文件上传失败" + error.message);}},// 重新选择reselect() {this.$confirm("重新选择比对结果会被清空?", "提示", {distinguishCancelAndClose: true,confirmButtonText: "确定",cancelButtonText: "取消",}).then(() => {this.uploaded = false;// console.log("dada");this.selectedFiles = []this.pdfsrc = ''this.loading = falsethis.$emit('upload', null)if (this.timer) {clearInterval(this.timer)}}).catch(() => { });},
</script>

第三步:实现本地文件渲染的 <embed> 标签

渲染机制:利用浏览器内置的 PDF 插件进行渲染

<embed v-if="pdfPreview" id="pdfPreview" :src="pdfPreview" width="100%" />

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

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/bicheng/80755.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Python 数据分析与可视化:开启数据洞察之旅(5/10)

一、Python 数据分析与可视化简介 在当今数字化时代&#xff0c;数据就像一座蕴藏无限价值的宝藏&#xff0c;等待着我们去挖掘和探索。而 Python&#xff0c;作为数据科学领域的明星语言&#xff0c;凭借其丰富的库和强大的功能&#xff0c;成为了开启这座宝藏的关键钥匙&…

C语言学习记录——深入理解指针(4)

OK&#xff0c;这一篇主要是讲我学习的3种指针类型。 正文开始&#xff1a; 一.字符指针 所谓字符指针&#xff0c;顾名思义就是指向字符的指针。一般写作 " char* " 直接来说说它的使用方法吧&#xff1a; &#xff08;1&#xff09;一般使用情况&#xff1a; i…

springboot3+vue3融合项目实战-大事件文章管理系统获取用户详细信息-ThreadLocal优化

一句话本质 为每个线程创建独立的变量副本&#xff0c;实现多线程环境下数据的安全隔离&#xff08;线程操作自己的副本&#xff0c;互不影响&#xff09;。 关键解读&#xff1a; 核心机制 • 同一个 ThreadLocal 对象&#xff08;如示意图中的红色区域 tl&#xff09;被多个线…

Nacos源码—8.Nacos升级gRPC分析六

大纲 7.服务端对服务实例进行健康检查 8.服务下线如何注销注册表和客户端等信息 9.事件驱动架构源码分析 一.处理ClientChangedEvent事件 也就是同步数据到集群节点&#xff1a; public class DistroClientDataProcessor extends SmartSubscriber implements DistroDataSt…

设计杂谈-工厂模式

“工厂”模式在各种框架中非常常见&#xff0c;包括 MyBatis&#xff0c;它是一种创建对象的设计模式。使用工厂模式有很多好处&#xff0c;尤其是在复杂的框架中&#xff0c;它可以带来更好的灵活性、可维护性和可配置性。 让我们以 MyBatis 为例&#xff0c;来理解工厂模式及…

AI与IoT携手,精准农业未来已来

AIoT&#xff1a;农业领域的变革先锋 在科技飞速发展的当下&#xff0c;人工智能&#xff08;AI&#xff09;与物联网&#xff08;IoT&#xff09;的融合 ——AIoT&#xff0c;正逐渐成为推动各行业变革的关键力量&#xff0c;农业领域也不例外。AIoT 技术通过将 AI 的智能分析…

排错-harbor-db容器异常重启

排错-harbor-db容器异常重启 环境&#xff1a; docker 19.03 , harbor-db(postgresql) goharbor/harbor-db:v2.5.6 现象&#xff1a; harbor-db 容器一直restart&#xff0c;查看日志发现 报错 initdb: error: directory "/var/lib/postgresql/data/pg13" exists…

Docker容器启动失败?无法启动?

Docker容器无法启动的疑难杂症解析与解决方案 一、问题现象 Docker容器无法启动是开发者在容器化部署中最常见的故障之一。尽管Docker提供了丰富的调试工具&#xff0c;但问题的根源往往隐藏在复杂的配置、环境依赖或资源限制中。本文将从环境变量配置错误这一细节问题入手&am…

查看购物车

一.查看购物车 查看购物车使用get请求。我们要查看当前用户的购物车&#xff0c;就要获取当前用户的userId字段进行条件查询。因为在用户登录时就已经将userId封装在token中了&#xff0c;因此我们只需要解析token获取userId即可&#xff0c;不需要前端再传入参数了。 Control…

C/C++ 内存管理深度解析:从内存分布到实践应用(malloc和new,free和delete的对比与使用,定位 new )

一、引言&#xff1a;理解内存管理的核心价值 在系统级编程领域&#xff0c;内存管理是决定程序性能、稳定性和安全性的关键因素。C/C 作为底层开发的主流语言&#xff0c;赋予开发者直接操作内存的能力&#xff0c;却也要求开发者深入理解内存布局与生命周期管理。本文将从内…

使用Stable Diffusion(SD)中CFG参数指的是什么?该怎么用!

1.定义&#xff1a; CFG参数控制模型在生成图像时&#xff0c;对提示词&#xff08;Prompt&#xff09;的“服从程度”。 它衡量模型在“完全根据提示词生成图像”和“自由生成图像”&#xff08;不参考提示词&#xff09;之间的权衡程度。 数值范围&#xff1a;常见范围是 1 …

【GESP】C++三级练习 luogu-B2156 最长单词 2

GESP三级练习&#xff0c;字符串练习&#xff08;C三级大纲中6号知识点&#xff0c;字符串&#xff09;&#xff0c;难度★★☆☆☆。 题目题解详见&#xff1a;https://www.coderli.com/gesp-3-luogu-b2156/ 【GESP】C三级练习 luogu-B2156 最长单词 2 | OneCoderGESP三级练…

Linux网络基础 -- 局域网,广域网,网络协议,网络传输的基本流程,端口号,网络字节序

目录 1. 计算机网络背景 1.1 局域网 1.1.2 局域网的组成 1.2 广域网 1.1.2 广域网的组成 2. 初始网络协议 2.1 网络协议的定义和作用 2.2 网络协议的分层结构 2.2.1 OSI七层模型 2.2.2 TCP/IP 五层&#xff08;四层&#xff09;模型 3. 再识网络协议 3.1 为什么要有…

【PostgreSQL】超简单的主从节点部署

1. 启动数据库 启动主节点 docker run --name postgres-master -e POSTGRES_PASSWORDmysecretpassword -p 5432:5432 -d postgres启动从节点 docker run --name postgres-slave -e POSTGRES_PASSWORDmysecretpassword -p 5432:5432 -d postgres需要配置挂载的存储卷 2. 数据…

c#修改ComboBox当前选中项的文本

对于一个C#的Combobox列表&#xff0c;类型设置为下拉样式&#xff0c;不允许输入&#xff0c;只能选择&#xff0c;样子如下&#xff1a; 该控件的名字为 cbb1&#xff0c;如果要修改当前这个“A1区”的文件&#xff0c;则用如下方式&#xff1a; cbb1.Items[cbb1.SelectedInd…

Java设计模式之适配器模式:从入门到精通

适配器模式(Adapter Pattern)是Java中最常用的结构型设计模式之一,它像一座桥梁连接两个不兼容的接口,使得原本由于接口不兼容而不能一起工作的类可以协同工作。本文将全面深入地解析适配器模式,从基础概念到高级应用,包含丰富的代码示例、详细注释、使用场景分析以及多维对…

中国黄土高原中部XF剖面磁化率和粒度数据

时间分辨率&#xff1a;1000年 < x空间分辨率为&#xff1a;空共享方式&#xff1a;申请获取数据大小&#xff1b;35.75 KB数据时间范围&#xff1a;743-0 ka元数据更新时间&#xff1a;2023-08-15 数据集摘要 该数据集包括中国黄土高原中部XF剖面磁化率和粒度数据。将所有…

【Python训练营打卡】day23 @浙大疏锦行

test pipeline管道 知识回顾: 1. 转化器和估计器的概念 2. 管道工程 3. ColumnTransformer和Pipeline类 作业&#xff1a; 整理下全部逻辑的先后顺序&#xff0c;看看能不能制作出适合所有机器学习的通用pipeline 伪代码 # 适合所有机器学习的通用pipeline #伪代码 import p…

【android bluetooth 框架分析 02】【Module详解 13】【CounterMetrics 模块介绍】

1. CounterMetrics 介绍 CounterMetrics 模块代码很少&#xff0c; 我简单介绍一下。 // system/gd/metrics/counter_metrics.cc #define LOG_TAG "BluetoothCounterMetrics"#include "metrics/counter_metrics.h"#include "common/bind.h" #i…

QMK键盘固件配置详解

QMK键盘固件配置详解 前言 大家好&#xff01;今天给大家带来QMK键盘固件配置的详细指南。如果你正在DIY机械键盘或者想要给自己的键盘刷固件&#xff0c;这篇文章绝对不容错过。QMK是目前最流行的开源键盘固件框架之一&#xff0c;它允许我们对键盘进行高度自定义。接下来&a…