uploadify文件上传以及预览
項目中利用poi實現預覽基本步驟:(其他的導入jar包什么的在別人資料上可以找到,我實現這個功能也是借鑒+實踐才成功的~我提供的只是我接觸項目的思路和代碼。見諒!【滑稽】)
先pdf,然后swf
安裝OpenOffice后啟動cmd:C:/Program Files (x86)/OpenOffice 4/program/soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\"
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?安裝路徑:C:/Program Files (x86)/OpenOffice 4/program/soffice.exe ;
1.(jsp頁面中)項目中uploadify上傳js格式
使用uploadify需要導入uploadify.css、jquery.uploadify.min.js等jar包,在官方domes有,嗯,有,還有各種屬性;
$('#file_upload').uploadify({'swf' : '${ctx}/js/uploadify3.2.1/uploadify.swf','uploader':'${ctx}/upload/uploadAction!uploadFile?jsessionid='+"<%=request.getParameter("fkId")%>",'buttonText' : '添加,'buttonClass' : 'uploadify','fileObjName' : 'uploadify','formData' : {'fkId' : '${fkId}'},'onUploadSuccess' : function(file, data, response) {}});});2.js中調用預覽的方法(只是提供一個js方法,放在jsp那里自己看咯) function preview(id) {var param = '';if(typeof id!='undefined')param = '&id='+id;var url='${ctx}/jsp/file/documentView.jsp?fkId='+fkId+param;window.top.art.dialog.open(url,{title:"在線預覽",width:'80%',height:'90%',lock:true,opacity:0.3,button: [ { name: '關閉', callback: function () {return true; }, focus: true }]});}
3.documentView.jsp頁面(項目數據)上面js方法中在線預覽內填充的頁面
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <%@ include file="/common/taglibs.jsp"%> <%@ include file="/common/jqueryhead.jsp" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html style="height: 100%;width: 100%;"> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <style type="text/css"> html, body { height:100%; }body { margin:0; padding:0; overflow:hidden; } /* #flashContent{display: none;} */#imgFile{width: 100%;height: 100%;display: none;}.module{display: none;}</style> <script type="text/javascript" src="${ctx}/jsp/file/js/swfobject/swfobject.js"></script><script type="text/javascript" src="${ctx}/jsp/file/js/flexpaper_flash.js"></script><script type="text/javascript">var imgSuffix="bmp,jpeg,gif,psd,png,tiff,tga,eps,jpg"; //常用圖片文件格式var mp4Suffix="mp4,avi,flv,rmvb,3gp"; //常用視頻格式var officeSuffix="txt,doc,xls,ppt,pdf,dwg,exb,docx,xlsx,pptx,wps,et,dps,html,xml,swf";$(function(){var fkId="${param.fkId}";var ids="${param.id}";console.log("documentView.jsp:"+fkId+"-----");//var ids="${param.id}";//讀取文件格式$.ajax({url:'${ctx}/upload/uploadAction!getFileStaff?ids='+ids,type:'post',data: "idd="+fkId ,async:false,success:function(data){console.log(data);data=eval('('+data+')');if(data.isExists=="false"){loadNoP(1); //文件不存在}else{var id=data.id;var pt=data.realName;var staff=data.extension;//文件格式console.log(id+"--"+staff+"==="+officeSuffix.indexOf(staff)+"----"+imgSuffix.indexOf(staff));if(imgSuffix.indexOf(staff)!=-1){ //是否是圖loadImage(pt);}else if(officeSuffix.indexOf(staff)!=-1){ //可預覽loadDocument(pt);}else{loadNoP(0);}}}});});/***預覽圖片 不需要轉換*/function loadImage(pt){$(".module").hide();console.log(pt+"");/* $("#imgFile").find("img").attr("src","${ctx}/downQybzh/downQybzhAction!preview?fkId=${param.id}"); */$("#imgFile").find("img").attr("src",pt);$("#imgFile").show();}/**不能預覽**/function loadNoP(status){$(".module").hide();if(status==1){$("#imgFile").find("img").attr("src","${ctx}/jsp/file/notExistsFile.jpg").attr("width","100%").attr("height","100%");}else{$("#imgFile").find("img").attr("src","${ctx}/jsp/file/descpreview.jpg").attr("width","100%").attr("height","100%");}$("#imgFile").show();}/***需要轉換*/<%-- function loadDocument(){$("#emb").attr("src","<%=session.getAttribute("swfpath")%>");$(".module").hide();$("#flashContent").show();} --%>function loadDocument(pt){console.log("loadDocument:"+pt);var fkId="${param.fkId}";var swfVersionStr = "9.0"; //版本var xiSwfUrlStr = "${ctx}/jsp/file/js/swfobject/expressInstall.swf";//播放器var flashvars={};flashvars = { //swf相對路徑 //SwfFile 后跟項目下的圖片路徑",SwfFile : decodeURI(pt),//SwfFile:escape('/pipe/upload/626ea0ed1e844eb5973005474701acdd測厚管線清單與記錄201704.swf'),Scale : 0.8, //Scale是0-1之間的數,表示顯示的放大參數 ZoomTransition : "easeOut", ZoomTime : 0.5, ZoomInterval : 0.1,FitPageOnLoad : false,FitWidthOnLoad : true,FitHeightOnload : true,PrintEnabled : false,FullScreenAsMaxWindow : false,ProgressiveLoading : true,// PrintToolsVisible : false,ViewModeToolsVisible : true,ZoomToolsVisible : true,FullScreenVisible : true,NavToolsVisible : true,CursorToolsVisible : true,SearchToolsVisible : true,WMode:"transparent",localeChain: "en_US",};var params = {};params.quality = "high";params.bgcolor = "#999999";params.allowscriptaccess = "sameDomain";params.allowfullscreen = "true";var attributes = {};attributes.id = "FlexPaperViewer";attributes.name = "FlexPaperViewer";swfobject.embedSWF("FlexPaperViewer.swf", "flashContent", "100%", "100%",swfVersionStr, xiSwfUrlStr, flashvars, params, attributes);swfobject.createCSS("#flashContent", "display:block;text-align:left;");$(".module").hide();$("#flashContent").show();};</script> </head> <body style="height: 100%;width: 100%;"><center><div style="height: 100%;width: 100%"><!-- 需要轉換的 --><div id="flashContent" class="module" style="height: 100%;width: 100%;" > 這里是預覽<!-- <EMBED id="emb" src="" style="height: 100%;width: 100%" type=application/x-shockwave-flash wmode="transparent "quality="high "></EMBED> --></div><!-- 圖片預覽 --><div id="imgFile" class="module" style="height: 100%;width: 100%"><img src="" width="100%" height="100%"/></div> <!-- 視頻預覽 --><div id="mp4Play" class="module" style="height: 100%;width: 100%" ><iframe width="100%" height="100%" frameborder="0" scrolling="no"></iframe></div></div></center></body> </html>
4.后臺判斷后綴方法
后面的兩行代碼:
? String json = new JsonMapper().toJson(ufi);
??Struts2Utils.renderText(json);
只是轉json數據格式;
public void getFileStaff() {fkId=request.getParameter("idd");Map<String, String> map = new HashMap<String, String>();map.put("fkId", fkId);List<UploadFileInfo> ufis = uploadFileInfoService.query(map);UploadFileInfo ufi = null;ufi = uploadFileInfoService.getById(request.getParameter("ids"));if (ufi != null) {String paths=null;try {paths=Encoding.encode(ufi.getName(), "UTF-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();}ufi.setIsExists("true");File file = new File(ufi.getDirectory() +request.getParameter("idd")+ paths);if (!file.exists()) {ufi.setIsExists("false");// 文件不存在uploadFileInfoService.delete(ufi.getId());}String converfilename = (ufi.getDirectory() +request.getParameter("idd")+ paths).replaceAll("\\\\", "/");String[] str={"bmp","jpeg","gif","psd","png","tiff","tga","eps","jpg"};String ext=ufi.getExtension();//判斷是否包含extboolean isContains = Arrays.asList(str).contains(ext);if(isContains){String realname=(request.getParameter("idd")+ paths).replaceAll("\\\\", "/");ufi.setRealName("/pipe/upload/"+realname);}else{DocConvert d=new DocConvert(converfilename);System.out.println("lujingming:"+d);d.conver();d.getswfPath();String swfpath = "/pipe/upload"+d.getswfPath().substring(d.getswfPath().lastIndexOf("/")); System.out.println("打印后的路徑:"+d.getswfPath());System.out.println("項目里的路徑:"+swfpath);ufi.setRealName(swfpath);}} else {ufi = new UploadFileInfo();ufi.setIsExists("false");// 文件不存在}String json = new JsonMapper().toJson(ufi);Struts2Utils.renderText(json);}5.工具類DocConvert
在上面判斷的方法中調用此類,用來啟動OpenOffice應用,進而轉換格式;
import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URLEncoder; import java.util.Properties;import com.artofsolving.jodconverter.DocumentConverter; import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection; import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection; import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter; import com.pacia.jfds.create.tools.Property;/** * doc docx格式轉換 */ @SuppressWarnings("all") public class DocConvert { private static final int environment =Integer.valueOf(Property.getProperty("environment")) ;// 環境 1:windows 2:linux private String fileString;// (只涉及pdf2swf路徑問題) private String outputPath = Property.getProperty("uploadFilePath");// 輸入路徑 ,如果不設置就輸出在默認的位置 private String fileName; private File pdfFile; private File swfFile; private File docFile; public DocConvert(String fileString) { ini(fileString); } /** * 重新設置file * @param fileString */ public void setFile(String fileString) { ini(fileString); } /** * 初始化 * @param fileString */ private void ini(String fileString) { this.fileString = fileString; fileName = fileString.substring(0, fileString.lastIndexOf(".")); docFile = new File(fileString); pdfFile = new File(fileName + ".pdf"); swfFile = new File(fileName + ".swf"); } /** * 轉為PDF * @param file */ private void doc2pdf() throws Exception { System.out.println("pdf轉換,,,,,,,,,,,,,,,");System.out.println("PDF文件路徑"+docFile);if (docFile.exists()) { if (!pdfFile.exists()) { // 調用openoffice服務線程String command = "C:/Program Files (x86)/OpenOffice 4/program/soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\"";Process p = Runtime.getRuntime().exec(command);// 連接openoffice服務// OpenOfficeConnection connection = new SocketOpenOfficeConnection(Integer.valueOf(Property.getProperty("port"))); //服務端口 portOpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1", 8100);try { connection.connect(); DocumentConverter converter = new OpenOfficeDocumentConverter(connection); converter.convert(docFile, pdfFile); // close the connection connection.disconnect(); // 關閉進程p.destroy();System.out.println("****pdf轉換成功,PDF輸出:" + pdfFile.getPath()+ "****1"); } catch (java.net.ConnectException e) { e.printStackTrace(); System.out.println("****swf轉換器異常,openoffice服務未啟動!****2"); throw e; } catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) { e.printStackTrace(); System.out.println("****swf轉換器異常,讀取轉換文件失敗****3"); throw e; } catch (Exception e) { e.printStackTrace(); throw e; } } else { System.out.println("****已經轉換為pdf,不需要再進行轉化****4"); } } else { System.out.println("****swf轉換器異常,需要轉換的文檔不存在,無法轉換****5"); } } /** * 轉換成 swf */ @SuppressWarnings("unused") private void pdf2swf() throws Exception { System.out.println("swf轉換。。。。。。。。。。。。。。"+swfFile.getPath());Runtime r = Runtime.getRuntime(); if (!swfFile.exists()) { if (pdfFile.exists()) {if (environment == 1) {// windows環境處理 try { //exePath+" "+pdfFile.getPath()+" -o "+swfFile.getPath()+" -T 9 -t -s storeallcharacters"//String paths=URLEncoder.encode(swfFile.getPath(), "UTF-8");Process p = r.exec(Property.getProperty("swfPath")+" "+ pdfFile.getPath() + " -o "+ swfFile.getPath() + " -T 9");System.out.println("---"+Property.getProperty("swfPath")+" "+ pdfFile.getPath() + " -o "+ swfFile.getPath() + " -T 9");System.out.print(loadStream(p.getInputStream())); System.err.print(loadStream(p.getErrorStream())); System.out.print(loadStream(p.getInputStream())); System.err.println("****swf轉換成功,文件輸出:" + swfFile.getPath() + "****6"); /* if (pdfFile.exists()) { pdfFile.delete(); } */ } catch (IOException e) { e.printStackTrace(); throw e; } } else if (environment == 2) {// linux環境處理 try { ///weblogic/wls1036/第四部分線性代數.pdf /weblogic/wls1036/1ssss1.swfStringBuffer file=new StringBuffer();file.append("pdf2swf -o ");file.append(swfFile.getPath());file.append(" -T -z -t -f ");file.append(pdfFile.getPath());file.append(" -s languagedir=/var/share/xpdf/xpdf-chinese-simplified -s flashversion=9"); // pdf2swf -o /var/lib/uploadsdsdf.swf -T -z -t -f /var/lib/upload/64d2020c24be4ab9989f82e874edd33f.pdf -s languagedir=/var/share/xpdf/xpdf-chinese-simplified -s flashversion=9 // String[] command = { "sh", "-c", "pdf2swf "+pdfFile.getPath() // + " -o " + swfFile.getPath() + " -T 9"};String[] command = { "/bin/sh", "-c", "pdf2swf "+pdfFile.getPath()+" "+swfFile.getPath()};// String command = "pdf2swf -z -s flashversion=9 " + pdfFile.getPath()+ " -o " + swfFile.getPath();System.out.println(command+" path"); // String[] command = { "/bin/sh", "-c", "pdf2swf "+pdfFile.getPath()+" "+swfFile.getPath()}; // Process p = r.exec("pdf2swf " + pdfFile.getPath() // + " -o " + swfFile.getPath() + " -T 9"); // System.out.println(command.toString()+"path"); // Process p=r.exec(command.toString());Process p=Runtime.getRuntime().exec(command);System.out.print(loadStream(p.getInputStream())); System.err.print(loadStream(p.getErrorStream())); System.err.println("****swf轉換成功,文件輸出:" + swfFile.getPath() + "****7"); /*if (pdfFile.exists()) { pdfFile.delete(); } */ } catch (Exception e) { e.printStackTrace(); throw e; } } } else { System.out.println("****pdf不存在,無法轉換****8"); } } else { System.out.println("****swf已經存在不需要轉換****9"); } } static String loadStream(InputStream in) throws IOException { int ptr = 0; in = new BufferedInputStream(in); StringBuffer buffer = new StringBuffer(); while ((ptr = in.read()) != -1) { buffer.append((char) ptr); } return buffer.toString(); } /** * 轉換主方法 */ public boolean conver() { if (swfFile.exists()) { System.out.println("****swf轉換器開始工作,該文件已經轉換為swf****10"); return true; } if (environment == 1) { System.out.println("****swf轉換器開始工作,當前設置運行環境windows****11"); } else { System.out.println("****swf轉換器開始工作,當前設置運行環境linux****12"); } try { doc2pdf(); pdf2swf(); } catch (Exception e) { e.printStackTrace(); return false; } if (swfFile.exists()) { return true; } else { return false; } } /** * 返回文件路徑 * @param s */ public String getswfPath() { if (swfFile.exists()) { String tempString = swfFile.getPath(); tempString = tempString.replaceAll("\\\\", "/"); return tempString; } else { return ""; } } /** * 設置輸出路徑 */ public void setOutputPath(String outputPath) { this.outputPath = outputPath; if (!outputPath.equals("")) { String realName = fileName.substring(fileName.lastIndexOf("/"), fileName.lastIndexOf(".")); if (outputPath.charAt(outputPath.length()) == '/') { swfFile = new File(outputPath + realName + ".swf"); } else { swfFile = new File(outputPath + realName + ".swf"); } } } }
總結
以上是生活随笔為你收集整理的uploadify文件上传以及预览的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: AD9导入CAD文件做封装外框
- 下一篇: 前端实现视频加速