Vue
js
// pdf 預覽
export function download(id) {
return request({
url: '/bbs/regtech/law/download?id='+id,
method: 'get',
responseType: "blob",
})
}
彈框方式打開/也可設置成在新頁面打開
<el-dialog
:title="title"
:visible.sync="viewVisible"
width="100%"
height="100%"
center
>
<template>
<iframe
class="prism-player"
:src="pdfUrl"
width="100%"
height="800px"
></iframe>
</template>
</el-dialog>
import { download } from "@/api/assistance";
export default {
data() {
return {
pdfUrl: "",
title: "",
viewVisible: false,
};
},
methods: {
gopdf() {
var id = "1515969321506050048";
download(id).then((res) => {
const binaryData = [];
binaryData.push(res.data);
let url = window.URL.createObjectURL(
new Blob(binaryData, { type: "application/pdf" })
);
this.pdfUrl = url;
// this.viewVisible = true; 當前頁彈框打開
// 新頁面打開
window.open(url);
});
},
},
};
Java 文件流輸出
@Override
public void download(HttpServletResponse response, String id) {
LawFile lawFile = this.getById(id);
String uploadPath = lawFile.getUploadPath();
String fileName = lawFile.getTitle();
try {
// 創建輸出流對象
ServletOutputStream outputStream = response.getOutputStream();
//以字節數組的形式讀取文件
byte[] bytes = FileUtil.readBytes(uploadPath);
// 設置返回內容格式
response.setContentType("application/octet-stream");
fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
// 設置下載彈窗的文件名和格式(文件名要包括名字和文件格式)
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
// 返回數據到輸出流對象中
outputStream.write(bytes);
// 關閉流對象
IoUtil.close(outputStream);
} catch (Exception ignored) {
log.error(ignored.getMessage());
}
}