Vue中前端接收二进制文件流实现预览PDF
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Vue中前端接收二进制文件流实现预览PDF相关的知识,希望对你有一定的参考价值。
参考技术A 1、后台Controller代码@GetMapping("/common/getPDFStream/key")
public void getPDFStream(@PathVariable String key,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException
FileStorage fileStorage = storageService.findByKey(key);
String type = fileStorage.getType();
MediaType mediaType = MediaType.parseMediaType(type);
Resource file = storageService.loadAsResource(key);
if (file == null)
response.setStatus(-1);
try
//文件所在的路径file.getURI().getPath()
File file1 = new File(file.getURI().getPath());
byte[] data = null;
FileInputStream input = new FileInputStream(file1);
data = new byte[input.available()];
input.read(data);
response.getOutputStream().write(data);
input.close();
catch (Exception e)
e.printStackTrace();
2、前台接收
封装axios, request.js
import axios from 'axios'
/**
* 封装axios异步请求的方法==================
*/
// 创建一个axios对象-----------
const request = axios.create(
baseURL:process.env.VUE_APP_BASE_API,//根据不同的环境,加载不同的常量值
timeout: 50000,//请求超时,50000毫秒
)
// 设置请求拦截器====================================
// 对拦截进行请求--------------------
request.interceptors.request.use(config =>
//请求拦截
config.data =
...config.data,
userId: sessionStorage.getItem('userId')
return config;
, error =>
//出现异常
return Promise.reject(error);//es6写法
);
// 设置响应拦截器==================================
// 对拦截进行响应--------------------
request.interceptors.response.use(response =>
if(!response.data||response.data=="")
return '"flag":"failure","msg":"未知错误"';
return response.data;
,error =>
return Promise.reject(error);
)
export default request //导出自定义创建的axios对象,供其他组件进行使用
3、定义方法 common.js
import request from '@/utils/request' //导入已经封装好的axios请求方式
export function getPDFStream(param)
// 定义后端请求路径
let url = process.env.VUE_APP_BASE_API + '/common/getPDFStream/' + fileKey
return request.get(url,
headers: 'Content-Type': 'application/x-www-form-urlencoded' ,
responseType: 'blob'
).then(async (data) =>
console.log('getPDFStream data', data)
const isLogin = await blobValidate(data.data)
console.log('download isLogin', isLogin)
if (isLogin)
const blob = new Blob([data.data], type: 'application/pdf')
return blob
else
const resText = await data.text()
const rspObj = JSON.parse(resText)
const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
Message.error(errMsg)
).catch((r) =>
console.error(r)
Message.error('下载文件出现错误,请联系管理员!')
)
4、vue页面代码
①触发事件列表标签
scope.row.courseName
②预览展示弹窗
<el-dialog p=""> </el-dialog>
width="900px"
title="预览"
:visible.sync="lookPdfFile"
:footer="null"
:forceRender="true"
@ok="lookPdfFile">
③ 需要导入方法、初始值、和自定义方法
// 在vue页面导入方法getPDFStream
import getPDFStream from "@/api/common";
// 在vue页面定义data
data ()
return
lookPdfFile:false,//预览pdf
pdfUrl:'',// pdf路径
// 在vue页面methods定义方法handlePDF
methods:
/** 课程预览 **/
async handlePDF(row)
console.log('handleLook', row)
this.getPDFStream(row.fileKey).then(res =>
console.log('res::::', res)
// debugger
if (window.createObjectURL !== undefined) // basic
this.pdfUrl = window.createObjectURL(res) + '#toolbar=0'
else if (window.webkitURL !== undefined) // webkit or chrome
try
this.pdfUrl = window.webkitURL.createObjectURL(res) + '#toolbar=0'
catch (error)
else if (window.URL !== undefined) // mozilla(firefox)
try
this.pdfUrl = window.URL.createObjectURL(res) + '#toolbar=0'
catch (error)
this.$nextTick(() =>
console.log('this.pdfUrl', this.pdfUrl)
this.lookPdfFile = true
)
)
以上是关于Vue中前端接收二进制文件流实现预览PDF的主要内容,如果未能解决你的问题,请参考以下文章