赞
踩
注意:
如果你复制我的代码到你的程序上报错,可以看看我第一篇文章实体类跟配置文件的设置:https://blog.csdn.net/qq_36688143/article/details/84162924
第二篇文件上传的代码:
https://blog.csdn.net/qq_36688143/article/details/84166676
1)需要下载LibreOffice
2)括号里的LibreOffice是这个程序的安装位置
- // 连接OpenOffice/LibreOffice服务 此地址为服务端安装项目路径,本地需要自行安装libreoffice
- OfficeManager officeManager = LocalOfficeManager.builder().officeHome(LibreOffice)
- .install().build();
- /* 本地LibreOffice的存储位置 */
- public static final String LibreOffice = "C:\\Program Files (x86)\\LibreOffice";
3)预览功能的后台代码
- /**
- * 预览
- * @param fileInfo
- * @param response
- * @throws Exception
- */
- @RequestMapping(value = "preview")
- public void preview(FileInfo fileInfo, HttpServletResponse response) throws Exception {
- response.setContentType("application/pdf");
- // 设置返回文件名
- response.setHeader("Content-Disposition",
- "inline; filename=" + new String((fileInfo.getFileName() + ".pdf").getBytes("UTF8"), "ISO8859_1"));
- try {
- // 从fastdfs中获取实际文件
- byte[] fileByte = fastDFSTemplate.loadFile(fileInfo.getFdfsGroup(),fileInfo.getFdfsPath());
- // 输出流
- OutputStream out = response.getOutputStream();
- // 是PDF就直接输出
- if ("PDF".equalsIgnoreCase(fileInfo.getFdfsPath().substring(fileInfo.getFdfsPath().indexOf(".")))){
- // 直接输出
- out.write(fileByte);
- }
- // 不是就做转换
- else {
- InputStream byteArrayInputStream = new ByteArrayInputStream(fileByte);
- ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
- // 此方法不能多线程使用
- synchronized (LocalOfficeManager.class) {
- // 连接OpenOffice/LibreOffice服务 此地址为服务端安装项目路径,本地需要自行安装libreoffice
- OfficeManager officeManager = LocalOfficeManager.builder().officeHome(LibreOffice)
- .install().build();
- try {
- // 服务启动
- officeManager.start();
- // 转换文档到pdf
- long time = System.currentTimeMillis();
- // 转换格式,注意:execute必须要用到,此为转换
- JodConverter.convert(byteArrayInputStream).as(fileInfo.getType()).to(byteArrayOutputStream)
- .as(DefaultDocumentFormatRegistry.PDF).execute();
- System.out.println("convert used :" + (System.currentTimeMillis() - time) + "ms");
- // 输出
- out.write(byteArrayOutputStream.toByteArray());
- } catch (OfficeException e) {
- e.printStackTrace();
- } finally {
- try {
- officeManager.stop();
- } catch (OfficeException e) {
- e.printStackTrace();
- }
- }
- }
- }
- out.flush();
- out.close();
- } catch (FastDFSException e) {
- e.printStackTrace();
- }
- }
4)预览功能的前端代码
不建议用<button/>,用<input type="button"/>代替。
- <input type="button" onclick="preview('${attachment.fileName}','${attachment.ext}','${attachment.fdfsGroup}','${attachment.fdfsPath}')"
- class="previewButton fontTypeTwo" value="预览"/>
JS部分
- /* 下载 */
- function download(fileName,fdfsGroup,fdfsPath) {
- location.href ="${ctx}/info/notice/download?fileName="+fileName+"&fdfsGroup="+fdfsGroup+"&fdfsPath="+fdfsPath;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。