package servlet; import java.io.File; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import util.Office2Swf; public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String inputFilePath = this.uploadFile(req); if (null != inputFilePath && !"".equals(inputFilePath.trim())) { String outFilePath = inputFilePath.replace(new File(inputFilePath).getName(), System.currentTimeMillis() + ".swf"); outFilePath = Office2Swf.office2Swf(inputFilePath, outFilePath); System.out.println("outFilePath:" + outFilePath); req.getSession().setAttribute("fileName", new File(outFilePath).getName()); } req.getRequestDispatcher("/readonline.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } @SuppressWarnings({"unchecked", "deprecation"}) private String uploadFile(HttpServletRequest request)throws ServletException, IOException { request.setCharacterEncoding("utf-8");//设置编码 //获得磁盘文件条目工厂 DiskFileItemFactory factory = new DiskFileItemFactory(); //获取文件需要上传到的路径 String path = request.getRealPath("/upload"); factory.setRepository(new File(path)); //设置缓存的大小,当上传文件的容量超过该缓存时,直接放到暂时存储室 factory.setSizeThreshold(1024*1024) ; //文件上传处理 ServletFileUpload upload = new ServletFileUpload(factory); String uploadFilePath = null; //可以上传多个文件 try { List<FileItem> list = (List<FileItem>)upload.parseRequest(request); for(FileItem item : list) { //获取表单的属性名字 String name = item.getFieldName(); // 表单文本信息 if(item.isFormField()) { String value = item.getString() ; request.setAttribute(name, value); } // 表单上传的文件 else { // 获取路径 String value = item.getName() ; int start = value.lastIndexOf("\\"); // 截取上传文件名称 String filename = value.substring(start+1); request.setAttribute(name, filename); item.write(new File(path,filename)); uploadFilePath = path + File.separator + filename; } } } catch (FileUploadException e) { e.printStackTrace(); } catch(Exception ex) { ex.printStackTrace(); } return uploadFilePath; } }
package util; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.regex.Pattern; import org.artofsolving.jodconverter.OfficeDocumentConverter; import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration; import org.artofsolving.jodconverter.office.OfficeManager; /** * * * @desc 需要OpenOffice第三插件的支持 ,支持window\linux\mac等系统 */ public class Office2PDF { public static final String[] OFFICE_POSTFIXS = { "doc", "docx", "xls", "xlsx", "ppt", "pptx" }; /** * 根据操作系统的名称,获取OpenOffice的安装目录 */ private static String getOfficeHome() { String osName = System.getProperty("os.name"); if (Pattern.matches("Linux.*", osName)) { return "/opt/openoffice4"; } else if (Pattern.matches("Windows.*", osName)) { return "D:/Program Files/SoftWare/work/openoffice"; } else if (Pattern.matches("Mac.*", osName)) { return "/Application/OpenOffice.org.app/Contents"; } return null; } /** * 转换文件 * * @param inputFilePath * 转换的office源文件路径 * @param outputFilePath * 输出目标文件路径 */ private static void converterFile(String inputFilePath, String outputFilePath) { File inputFile = new File(inputFilePath); File outputFile = new File(outputFilePath); // 假如目标路径不存在,则新建该路径 if (!outputFile.getParentFile().exists()) { outputFile.getParentFile().mkdirs(); } DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration(); // 获取OpenOffice 的安装目录 String officeHome = getOfficeHome(); config.setOfficeHome(officeHome); // 启动OpenOffice的服务 OfficeManager officeManager = config.buildOfficeManager(); officeManager.start(); OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager); converter.convert(inputFile, outputFile); System.out.println("文件:" + inputFilePath + "\n转换为\n目标文件:" + outputFile + "\n成功!"); officeManager.stop(); } /** * 将(.doc|.docx|.xls|.xlsx|.ppt|.pptx)等office文件 转化为pdf文件 * * @param inputFilePath * 待转换的源文件路径 * @param outputFilePath * 输出的目录文件路径,如果未指定(null),则按在源文件当前目录生成同名的pdf文件 * @return 处理结果 */ public static boolean openOffice2Pdf(String inputFilePath, String outputFilePath) { boolean flag = false; File inputFile = new File(inputFilePath); ArrayList<String> office_Formats = new ArrayList<String>(); Collections.addAll(office_Formats, OFFICE_POSTFIXS); if ((null != inputFilePath) && (inputFile.exists())) { // 判断目标文件路径是否为空 if (office_Formats.contains(getPostfix(inputFilePath))) { if (null == outputFilePath) { // 转换后的文件路径 String outputFilePath_new = inputFilePath.toLowerCase().replaceAll("." + getPostfix(inputFilePath), ".pdf"); converterFile(inputFilePath, outputFilePath_new); flag = true; } else { converterFile(inputFilePath, outputFilePath); flag = true; } } } return flag; } /** * 获取文件的后缀名 */ private static String getPostfix(String inputFilePath) { String[] p = inputFilePath.split("\\."); if (p.length > 0) { return p[p.length - 1]; } else { return null; } } }
package util; import java.io.File; import java.util.regex.Pattern; /** * * * @desc 需要swftools第三插件的支持 ,支持window\linux\mac等系统 */ public class Office2Swf { /** * 根据操作系统的名称,获取执行pdf->swf文件的命令 * * @param pdfFile * 转换的pdf源文件路径 * @param swfOutFilePath * 输出的swf文件路径 * @return */ private static String getCommand(String pdfFile, String swfOutFilePath) { String command = null; String osName = System.getProperty("os.name"); if (null == swfOutFilePath || "".equals(swfOutFilePath.trim())) { swfOutFilePath = pdfFile.toLowerCase().replaceAll(".pdf", ".swf"); } if (Pattern.matches("Linux.*", osName)) { command = "pdf2swf " + pdfFile + " " + swfOutFilePath + " -T 9 -f -s languagedir=/usr/local/xpdf/xpdf-chinese-simplified/CMap"; } else if (Pattern.matches("Windows.*", osName)) { command = "D:/Program Files/SoftWare/work/swftools/pdf2swf.exe -t " + pdfFile + " -o " + swfOutFilePath + " -T 9 -f"; } else if (Pattern.matches("Mac.*", osName)) { } return command; } /** * 将pdf转换swf文件,在线预览 * * @param pdfInputFilePath * 待转换的pdf源文件路径 * @param swfOutFilePath * 输出的swf目标文件路径,如果未指定(null),则按在源文件当前目录生成同名的swf文件 * @return swf目标文件路径 */ public static String pdf2Swf(String pdfInputFilePath, String swfOutFilePath) { String command = getCommand(pdfInputFilePath, swfOutFilePath); System.out.println("pdfInputFilePath" + pdfInputFilePath); try { Process pro = Runtime.getRuntime().exec(command); pro.waitFor(); return pdfInputFilePath.replaceAll("." + getPostfix(pdfInputFilePath), ".swf"); } catch (Exception ex) { ex.printStackTrace(); } return null; } /** * 将office文件直接转换为swf文件 * * 如果是pdf直接轉換 * * @param inputFilePath * 待转换的源office文件路径 * @param outputSwfPath * 输出的swf目标文件路径,如果未指定(null),则按在源文件当前目录生成同名的swf文件 * @return swf目标文件路径 */ public static String office2Swf(String inputFilePath, String outputSwfPath) { String outputPdfPath = null; if ("pdf".equals(getPostfix(inputFilePath))) { String swfName = new File(outputSwfPath).getName(); String pdfName = new File(inputFilePath).getName(); String new_swfName = swfName.replace("." + getPostfix(outputSwfPath), ".pdf"); outputPdfPath = inputFilePath.replace(pdfName, new_swfName); File old_inputFilePath = new File(inputFilePath); File new_outputPdfPath = new File(outputPdfPath); old_inputFilePath.renameTo(new_outputPdfPath); // 把pdf重命名 outputSwfPath = pdf2Swf(outputPdfPath, outputSwfPath); } else { if (null == outputSwfPath || "".equals(outputSwfPath.trim())) { outputPdfPath = inputFilePath.replace("." + getPostfix(inputFilePath), ".pdf"); } else { outputPdfPath = outputSwfPath.replace("." + getPostfix(outputSwfPath), ".pdf"); } boolean isSucc = Office2PDF.openOffice2Pdf(inputFilePath, outputPdfPath); if (isSucc) { outputSwfPath = pdf2Swf(outputPdfPath, outputSwfPath); } } return outputSwfPath; } /** * 获取文件的后缀名 */ private static String getPostfix(String inputFilePath) { String postfix = null; if (null != inputFilePath && !"".equals(inputFilePath.trim())) { int idx = inputFilePath.lastIndexOf("."); if (idx > 0) { postfix = inputFilePath.substring(idx + 1, inputFilePath.trim().length()); } } return postfix; } }
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <html> <head> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> </head> <body> <form action="uploadServlet" enctype="multipart/form-data" method="post"> <font style="color:red">只支持office文件在线预览,如doc,docx,ppt,pptx,xls,xlxs,pdf</font><br/> <input type="file" name="file"/><br/> <input type="submit" value="在线预览"> </form> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="zh-CN"> <head> <title>在线预览</title> <script type="text/javascript" src="FlexPaper/js/jquery.js"></script> <script type="text/javascript" src="FlexPaper/js/flexpaper_flash.js"></script> <script type="text/javascript" src="FlexPaper/js/flexpaper_flash_debug.js"></script> </head> <%-- <%=(String)session.getAttribute("fileName")%> --%> <body> <div ><!-- 设置显示位置 --> <%-- 指定flexPaper的宽度和高度 --%> <a id="viewerPlaceHolder" style="width:100%;height:100%;display:block"></a> <script type="text/javascript"> var fp = new FlexPaperViewer( \'FlexPaper/swfFiles/FlexPaperViewer\', \'viewerPlaceHolder\', { config : { SwfFile : escape(\'upload/<%=(String)session.getAttribute("fileName")%>\'), Scale : 1, ZoomTransition : \'easeOut\', ZoomTime : 0.5, ZoomInterval : 0.2, /* 缩放滑块-移动的缩放基础[工具栏] */ FitPageOnLoad : true, /*自适应页面 */ FitWidthOnLoad : true, /*自适应宽度 */ PrintEnabled : true, FullScreenAsMaxWindow : false, /*全屏按钮-新页面全屏[工具栏] */ ProgressiveLoading : false, /*分割加载 */ MinZoomSize : 0.2, /*最小缩放 */ MaxZoomSize : 5, /*最大缩放 */ SearchMatchAll : false, /* */ InitViewMode : \'Portrait\', /* 初始显示模式(SinglePage,TwoPage,Portrait) */ ViewModeToolsVisible : true, /*显示模式工具栏是否显示 */ ZoomToolsVisible : true, /* 缩放工具栏是否显示 */ NavToolsVisible : true, /*跳页工具栏 */ CursorToolsVisible : true, /* */ SearchToolsVisible : true, /* */ localeChain: \'zh_CN\' }}); </script> </div> </body> </html>