#头条创作挑战赛#
xx,我们的pdf文档需要做一个预览功能,你今天加班做一下吧。。。
环境: 文件服务器: fastdfs 前端:vue 后段:springboot
单纯的使用pdf.js进行预览出现了跨域问题,所以需要后端把文件流传给前端,然后前端进行展示。
1.下载pdf.js: http://mozilla.github.io/pdf.js/getting_started/#download,如果无法打开,下载我存放的已经修改过的pdf.js:https://download.csdn.net/download/weixin_42551369/20005008
2. 将下载好的文件中的build和web拷贝到vue项目的public文件夹下
3. 上代码
3.1 vue前端
3.2 java后端
3.2.1 controller层
/**
* pdf 预览功能
*
* @param response
* @param fileUrl
*/
@GetMapping("/readPdfFile")
public void previewPdf(HttpServletResponse response , String fileUrl){
ExportFileUtil.preview(response, fileUrl);
}
3.2.2 service层
/**
* 文件预览
* @param response
* @param filePath
*/
public static void preview(HttpServletResponse response, String filePath) {
ServletOutputStream out;
BufferedInputStream buf;
try {
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "inline;fileName=" + filePath.substring(filePath.lastIndexOf("/") + 1));
URL url = new URL(filePath);
//使用输入读取缓冲流读取一个文件输入流
buf = new BufferedInputStream(url.openStream());
//利用response获取一个字节流输出对象
out = response.getOutputStream();
//定义个数组,由于读取缓冲流中的内容
byte[] buffer = new byte[1024];
int n;
//while循环一直读取缓冲流中的内容到输出的对象中
while ((n = buf.read(buffer)) != -1) {
out.write(buffer, 0, n);
}
//写出到请求的地方
out.flush();
buf.close();
out.close();
} catch (IOException e) {
StaticLog.error("ExportFileUtil.download() IOException", e);
} catch (Exception e) {
StaticLog.error("Exception", e);
}
}
4.看效果
5.成功~~~
demo地址-github:https://github.com/1137854811/pdf_js
demo地址-gitee:https://gitee.com/TZWw/preview-pdf