VUE
<template>
<div id="app">
<el-dialog
ref="previewPdf"
:visible.sync="open"
:modal="true"
width="100%"
title="pdf预览"
append-to-body>
<iframe
width="100%"
height="800px"
frameborder="0"
:src="pdfSrc">
</iframe>
</el-dialog>
</div>
</template>
<script>
import {
getToken
} from '@/public/utils/auth'
import axios from 'axios'
export default {
name: "previewPdf",
data() {
return {
open:false,
pdfSrc:'',
requestUrl:process.env.VUE_APP_BASE_API //全局请求url
}
},
created() {
this.showData()
},
methods: {
showData(id) { //请求接口后处理 最终得到pdfSRC
axios({
method: 'GET',
url: this.requestUrl + '/baseIndex/viewPdfCorp/',
responseType: 'blob',
headers: { 'Authorization': 'Bearer ' + getToken() } //token
}).then(res => {
this.id=id;
const blobData = {}
blobData.type = 'application/pdf;chartset=UTF-8'
this.pdfSrc = window.URL.createObjectURL(new Blob([res.data], blobData))
this.loading = false
})
},
previewPdf(path) { //父组件调用
this.open = true;
if (path != null && path != undefined) {
this.pdfSrc = path;
}
},
}
}
</script>
<style scoped>
</style>
JAVA
@Value("${hxzk.profile}")
private String uploadPath; //读取Applicion的默认文件存储路径
@GetMapping("viewPdfCorp")
public void viewPdfCorp(HttpServletResponse response) {
previewPdf(uploadPath+File.separator+"pdf","980fa5dff63f46a3a4e4b8943e28806c.pdf",response);
}
/**
* pdf预览、下载
* @author huangjie
* @date 2022-8-5 17:31
* @param fileName 文件名
* @param path 文件路径
* @return void
*/
public static void previewPdf(String path,String fileName, HttpServletResponse response){
String pdfPath = path+File.separator+ fileName;
// 验证该文件是否是存在
if(new File(path+File.separator+fileName).exists()){
//添加跨域访问
//以流的形式传输
response.setContentType("application/octet-stream");
// 设置文件流编码格式
response.setCharacterEncoding("UTF-8");
//Content-Disposition属性名 (attachment表示以附件的方式下载;inline表示在页面内打开)
response.setHeader("Content-Disposition", "attachment; fileName="+fileName+".pdf");
try { //输入输出
FileInputStream is = new FileInputStream(pdfPath);
ServletOutputStream out = response.getOutputStream();
byte[] buffer = new byte[1024];
int i = 0;
while ((i = is.read(buffer)) != -1) {
out.write(buffer,0,i);
}
//缓存区的数据进行输出
out.flush();
//关闭流
out.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}