前端上傳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.pswp.cn/bicheng/80755.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/80755.shtml
英文地址,請注明出處:http://en.pswp.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…