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");                }            }        }    }




原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 电子录入系统中无法打开影像怎么办 火车票退票后说银行退款失败怎么办 苹果4s玩游戏闪退怎么办 买了二手房原房主不迁户口怎么办 苹果禁反忘记工id密码了怎么办 玩英雄联盟用腾讯游戏平台卡怎么办 游戏代练接单了没有给我账号怎么办 华为手机进入设置立即闪退怎么办 股东发现公司有做假账现象怎么办 中国在服役期间有纹身被发现怎么办 脚碰了肿了紫了怎么办 外阴出血了怎么办去医院检查没问题 三个半月宝宝体检脚有的紧怎么办 肛门被红枣核刺了一个洞怎么办 肛门里面有棉签上的棉花怎么办 孩子裤子沾屎怎么洗下来怎么办 做完痔疮手术后有点肛门狭窄怎么办 孕妇做b超宝宝不配合怎么办 怀孕产检医生问的尴尬怎么办 带着节育环做的核磁怎么办 便秘洗肠后最一周未排便怎么办 用了开塞露后肚子疼拉不出来怎么办 冰点脱毛当天用沐浴露洗澡了怎么办 自体脂肪填充脸部但发红又痒怎么办 金矿受伤死亡不给开死亡证明怎么办 手机欠费了导致没信号了怎么办 金立手机指纹硬件无法使用怎么办 试管取卵医生说卵子碎片多怎么办 取卵腹水抽水后尿不通怎么办 手机锁屏密码忘了怎么办求解锁 苹果手表锁屏密码忘记了怎么办 苹果手表锁屏密码忘了怎么办 电脑输密码时点了用户账户怎么办 w7电脑锁屏密码忘记了怎么办 台式电脑w7锁屏密码忘记了怎么办 win7电脑锁屏密码忘记了怎么办 苹果手机4s开机密码忘记了怎么办 苹果4s下载东西忘记密码怎么办 苹果4s不记得开机密码怎么办? 苹果手机id密码忘了怎么办能解锁 苹果5s id密码忘了怎么办?