uploadify文件上传以及预览
来源:互联网 发布:java jdk jre下载官网 编辑:程序博客网 时间:2024/06/07 12:20
项目中利用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"))); //服务端口 port OpenOfficeConnection 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.swf StringBuffer 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"); } } } }
阅读全文
0 0
- uploadify文件上传以及预览
- Structs2文件上传以及预览
- uploadify+java实现多文件上传和预览
- Uploadify 控件上传图片 + 预览
- uploadify上传后预览Demo
- form表单文件上传以及预览
- JQuery文件上传插件Uploadify介绍以及用法
- uploadify批量上传文件
- jquery uploadify 上传文件
- uploadify实现文件上传
- uploadify批量上传文件
- 文件上传[Uploadify]
- uploadify多文件上传
- 使用uploadify上传文件
- uploadify 文件上传 struts2
- uploadify上传文件
- uploadify 上传大文件
- uploadify上传文件功能
- StringUtils api 中文 英文 对照
- 前端的发展史
- 将eChart图片利用POI导出到Excel
- 微信小程序 清空或修改input值 的方法
- xencenter如何安装Centos7虚拟机系统
- uploadify文件上传以及预览
- Python字符串常用方法收藏
- Java趣味赏玩
- 类、对象、属性、方法和事件的概念辨析
- 机器学习实战_12FP-growth算法发现高频项集
- CardStackView使用教程
- Uva12096
- SQL 查询优化 索引优化
- RecyclerView中Adapter调用notifyDataSetChanged无效时的解决方案