Vue中接收二進(jìn)制文件流實(shí)現(xiàn)pdf預(yù)覽的方法
后臺(tái)Controller
@RequestMapping("/getPDFStream") @ResponseBody public void getPDFStream(HttpServletRequest request,HttpServletResponse response) { try { request.setCharacterEncoding("utf-8"); } catch (UnsupportedEncodingException e) { logger.error("設(shè)置字符集UnsupportedEncodingException"); } String fileName = request.getParameter("fileName"); //文件路徑 String filePathname = Const.UPLOAD_HBFILE_PATH + "/" + fileName + ".pdf"; File file = new File(filePathname); byte[] data = null; if (!file.exists()) { logger.error("Sorry File does not Exists!"); } else { try { FileInputStream input = new FileInputStream(file); data = new byte[input.available()]; input.read(data); response.getOutputStream().write(data); input.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); logger.error("pdf文件處理異常"); } } }
前臺(tái)接收
封裝axios, request.js
import axios from 'axios' /** * 封裝axios異步請求的方法================== */ //創(chuàng)建一個(gè)axios對(duì)象----------- const request = axios.create({ //baseURL:'/dev-api',//基礎(chǔ)路徑 baseURL:process.env.VUE_APP_BASE_API,//根據(jù)不同的環(huán)境,加載不同的常量值 // baseURL: '/', timeout: 50000,//請求超時(shí),50000毫秒 }) //設(shè)置請求攔截器==================================== //對(duì)攔截進(jìn)行請求-------------------- request.interceptors.request.use(config => { //請求攔截 config.data = { ...config.data, userId: sessionStorage.getItem('userId') } return config; }, error => { //出現(xiàn)異常 return Promise.reject(error);//es6寫法 }); //設(shè)置響應(yīng)攔截器================================== //對(duì)攔截進(jìn)行響應(yīng)-------------------- request.interceptors.response.use(response =>{ if(!response.data||response.data==""){ return '{"flag":"failure","msg":"未知錯(cuò)誤"}'; } return response.data; },error =>{ return Promise.reject(error); }) export default request //導(dǎo)出自定義創(chuàng)建的axios對(duì)象,供其他組件進(jìn)行使用
定義方法 common.js
import request from '@/utils/request' //導(dǎo)入已經(jīng)封裝好的axios請求方式 export function getPDFStream(param) { return request({ url: 'xxxxxx/getPDFStream', method: 'post', //傳遞參數(shù) data: param, headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, responseType: 'blob', transformRequest: function(obj) { var str = []; for (var p in obj) str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); return str.join("&"); }, }) }
頁面代碼
<a-modal width="900px" title="文件查看" v-model="lookPdfFile" :footer="null" :forceRender="true" @ok="lookPdfFile" > <div :style="{ height: '600px', minHeight: '500px', margin: '8px 0px' }"> <iframe :src="pdfUrl" id="previewPdf" frameborder="0" style="width: 100%; height: 100%"></iframe> </div> </a-modal>
//導(dǎo)入方法 import {getPDFStream} from "@/api/common"; //定義data lookPdfFile:false,//預(yù)覽pdf pdfUrl:'',// pdf路徑
關(guān)鍵代碼(獲取文件名稱后調(diào)用getPDFStream方法獲取文件流)
let _this = this; if(suffix == 'pdf'){ getPDFStream({ fileName: filename, }).then(res => { let reader = new window.FileReader(); // 使用readAsArrayBuffer讀取文件, result屬性中將包含一個(gè) ArrayBuffer 對(duì)象以表示所讀取文件的數(shù)據(jù) reader.readAsArrayBuffer(res); reader.onload = function(e) { const result = e.target.result const contentType = res.type // 生成blob圖片,需要參數(shù)(字節(jié)數(shù)組, 文件類型) const blob = new Blob([result], { type: 'application/pdf' }) // 使用 Blob 創(chuàng)建一個(gè)指向類型化數(shù)組的URL, URL.createObjectURL是new Blob文件的方法,可以生成一個(gè)普通的url,可以直接使用,比如用在img.src上 if (window.createObjectURL != undefined) { // basic _this.pdfUrl = window.createObjectURL(blob)+'#toolbar=0' } else if (window.webkitURL != undefined) { // webkit or chrome try { _this.pdfUrl = window.webkitURL.createObjectURL(blob)+'#toolbar=0' } catch (error) { } } else if (window.URL != undefined) { // mozilla(firefox) try { _this.pdfUrl = window.URL.createObjectURL(blob)+'#toolbar=0' } catch (error) { } } } this.$nextTick(() => { this.lookPdfFile = true; }) }) return; }
到此這篇關(guān)于Vue中接收二進(jìn)制文件流實(shí)現(xiàn)pdf預(yù)覽的方法的文章就介紹到這了,更多相關(guān)Vue 二進(jìn)制文件流pdf預(yù)覽內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!?
相關(guān)文章
Vue開發(fā)實(shí)現(xiàn)吸頂效果的示例代碼
這篇文章主要介紹了Vue開發(fā)實(shí)現(xiàn)吸頂效果的示例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-08-08Vue實(shí)現(xiàn)路由嵌套的方法實(shí)例
嵌套路由顧名思義就是路由的多層嵌套,這篇文章主要給大家介紹了關(guān)于Vue實(shí)現(xiàn)路由嵌套的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2021-11-11Vue裝飾器中的vue-property-decorator?和?vux-class使用詳解
這篇文章主要介紹了Vue裝飾器中的vue-property-decorator?和?vux-class使用詳解,通過示例代碼給大家介紹的非常詳細(xì),對(duì)vue-property-decorator?和?vux-class的使用感興趣的朋友一起看看吧2022-08-08Vue3+elementui plus創(chuàng)建項(xiàng)目的方法
這篇文章主要介紹了Vue3+elementui plus創(chuàng)建項(xiàng)目的方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12vue中的this.$router.push()路由傳值方式
這篇文章主要介紹了vue中的this.$router.push()路由傳值方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-10-10