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異步請(qǐng)求的方法==================
*/
//創(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,//請(qǐng)求超時(shí),50000毫秒
})
//設(shè)置請(qǐng)求攔截器====================================
//對(duì)攔截進(jìn)行請(qǐng)求--------------------
request.interceptors.request.use(config => {
//請(qǐng)求攔截
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請(qǐng)求方式
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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!?
相關(guān)文章
Vue路由切換和Axios接口取消重復(fù)請(qǐng)求詳解
在web項(xiàng)目開發(fā)的過程中,經(jīng)常會(huì)遇到客服端重復(fù)發(fā)送請(qǐng)求的場(chǎng)景,下面這篇文章主要給大家介紹了關(guān)于Vue路由切換和Axios接口取消重復(fù)請(qǐng)求的相關(guān)資料,需要的朋友可以參考下2022-05-05
基于Vue3+TypeScript實(shí)現(xiàn)鼠標(biāo)框選功能
這篇文章主要介紹了基于Vue3+TypeScript實(shí)現(xiàn)鼠標(biāo)框選功能,文中通過代碼示例給大家講解的非常纖細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-07-07
詳解如何使用 vue-cli 開發(fā)多頁應(yīng)用
本篇文章主要介紹了詳解如何使用 vue-cli 開發(fā)多頁應(yīng)用,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-12-12

