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文件上传以及预览相关推荐
- uploadify java 下载_uploadify java实现多文件上传和预览
本文实例为大家分享了java文件上传和预览实现代码,供大家参考,具体内容如下 1.下载uploadify插件 2.index.html #uploader { position: relative; ...
- php 表格导入excel插件,BootStrap Fileinput插件和表格插件相结合实现导入Excel数据的文件上传、预览、提交的步骤...
这篇文章主要介绍了BootStrap Fileinput插件和Bootstrap table表格插件相结合实现文件上传.预览.提交的导入Excel数据操作步骤,需要的朋友可以参考下 bootstrap ...
- php案例 文件上传并预览
作者:陈业贵 华为云享专家 51cto(专家博主 明日之星 TOP红人) 阿里云专家博主 文章目录 前言 代码 cyg.php 2.php 效果:也就是上传的文件里面的内容 前言 php案例 文件上传 ...
- servlet实现文件上传,预览,下载和删除
一.准备工作 1.1 文件上传插件:uploadify: 1.2 文件上传所需jar包:commons-fileupload-1.3.1.jar和commons-io-2.2.jar 1.3 将数据转 ...
- kl-uploads 多文件上传与预览的实现
功能描述 多文件的上传,图片添加预览功能,非图片只有名称列表 使用 <template><div class="demo"><klUploadhide ...
- javascript --- 文件上传即时预览 闭包实现多图片即时预览
使用javascript原生功能实现,点击上传文件,然后再网页上显示出来 1. 初级显示 1.1 准备一个input标签和一个img标签 <input type=file id="fi ...
- JQ input 文件上传并预览 选择图片后,在页面上预览图片,页面渲染
有时候,我们更新界面信息时会遇到,选择图片后,并不能预览图片,必须提交数据库后才能在页面上显示出来,这样我们该怎样办呢? 起始jq为我们提供了两个方法change()和URL.createObject ...
- minio实现大文件分片上传+断点续传+预览
minio实现大文件分片上传+断点续传+预览 只提供后端java代码 思路: 前端分片 校验文件md5是否已经存在 --不存在创建临时桶存分片 校验分块是否已经上传 分块上传 合并分块 校验合成后md ...
- alert()的功能_前端实现简单的图片上传小图预览功能
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8" ...
- DevExpress控件使用系列--ASPxUploadControl(图片上传及预览)
1.控件功能 列表控件展示数据.弹框控件执行编辑操作.Tab控件实现多标签编辑操官方说明 2.官方示例 2.1 ASPxImage http:// ...
最新文章
- struts2框架之国际化(参考第二天学习笔记)
- 软件生成目录没有图框_图纸目录和编号
- python PyQt5 QVBoxLayout 垂直布局管理
- 天翼云从业认证(4.6)高并发场景上云实践
- python源码精要(10)-python源代码阅读概要(1)
- CPU,寄存器,内存三者的关系
- 朝着理想坚实迈进_坚实原则:开放/封闭原则
- 1.2)深度学习笔记------神经网络的编程基础
- webpack打包原理
- 字符串解析成easyui-tree的格式
- 哈工大刘挺教授:中文信息处理前沿技术进展
- 学嵌入式必须掌握的经验
- python3: failed with error code 1 in /tmp/pip-build-qp5puacl/Pillow/
- 趣学Python 教孩子学编程pdf
- w ndows10卸载word,windows10系统下怎样卸载office 2003
- C#在word中插入表格(包含从excel中选取表格插入到word中)
- 脑神经科学简单介绍(小白入门)
- 1.4 裸机实验GPIO与LED DNW驱动无法安装问题解决
- EMC中的基石-电磁兼容滤波知识大全!
- 二叉树:已知先序和中序求后序,已知中序和后序求先序
热门文章
- 计算机中内存存储器最小单位,计算机中存储容量的最小单位和最基本单位是什么?...
- 动易sitefactory 3.0 模板标签系统
- 数据挖掘:概念与技术(第三版)之第四章的学习记录
- GNU大型项目构建和覆盖率生成(第一篇)
- ttl备份机顶盒固件_机顶盒刷机TTL教程,任意安装安卓软件,免费看电视直播
- 老男孩linux学习笔记第一课安装Linux
- 数字盲打怎么练_键盘上的数字键怎么练才能盲打?
- 老司机带你用python爬取妹子图,接稳这波福利
- 【渝粤题库】广东开放大学 大学生创业基础 形成性考核
- 3dmax无法显示缩略图 或者 缩略图显示为黑色 -解决方法