后臺(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'
//創(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("&");
},
})
}
頁(yè)面代碼
<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;
}
|