赞
踩
大致流程
后端传数据流,前端已Blob的形式接收,Blob转化成URL直接在浏览器打开。
Vue
两种形式:①直接在浏览器打开URL,打开后可以在PDF里面下载;②直接下载PDF
private async handleInfo(row: any) { const { data,headers } = await read(row.name); console.log(headers) const url = window.URL.createObjectURL( new Blob([data], { type: "application/pdf;charset=UTF-8;" }) ); const link = document.createElement("a"); link.href = url; // 下载的代码 // link.setAttribute("download", 'test'); // document.body.appendChild(link); // link.click(); // document.body.removeChild(link); window.open(url); // 直接打开预览的代码 setTimeout(() => { this.loading = false; }, 0.5 * 1000); }
API
文件以Blob的形式接收
export const readPDF =(name: string) =>
request({
url: `/api/file/readPDF/${name}`,
responseType: 'blob'
});
Service.java
void readPDF(Integer id, HttpServletResponse response) throws IOException();
ServiceImpl.java
public void readPDF(Integer id, HttpServletResponse response) throws IOException { // 预览/下载PDF文件 String filename = URLEncoder.encode("PDF" ,"UTF-8"); response.setContentType("application/pdf"); response.setHeader("filename",""+ filename + ".pdf"); response.addHeader("Access-Control-Expose-Headers", "filename"); // 获取数据库中的二进制数据 QueryWrapper<File> queryWrapper = new QueryWrapper<File>() //利用mybatisPlus按id查询 .eq("id",id); File file = fileMapper.selectOne(queryWrapper); ByteArrayInputStream in = new ByteArrayInputStream(file.getData()); OutputStream out = response.getOutputStream(); byte[] bytes = new byte[1024]; while((in.read(bytes)) != -1) { out.write(bytes); } out.flush(); in.close(); out.close(); }
Controller.java
application/octet-stream:以二进制流的方式传输文件,只能传输一个。
@GetMapping(
value = "/getPDF/{id}",
produces = {"application/octet-stream;charset=UTF-8"}
)
public void readPDF(@PathVariable Integer id, HttpServletResponse response) throws IOException {
fileService.read(id,response);
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。