Vue 文件流预览 PDF
js
// pdf 预览
export function pdfYL(foreId) {
return request({
url: '/bbs/regtech/law/download?id='+foreId,
method: 'get',
responseType: "blob",
})
}
import { pdfYL } from "@/api/api";
export default {
data() {
return {
pdfUrl: "",
title: "",
viewVisible: false,
};
},
methods: {
YLpdf() {
var id = '获取到的id获传参';
pdfYL(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());
}
}