转自:http://www.cnblogs.com/java_cSharp/archive/2011/08/06/KindEditor_upload_image_plugin.html
前序:由于工作需要使用在线编辑器,找了几个对比了下KindEditor还是不错的,国产的.但文档还是不全,还好能参考官方插件,套出来一些插件.本文章分为4个部分,分别介绍图片上传插件、代码高亮插件、引用文本以及附件插件的制作。网上大部分都是直接或改官方的JSP文件,连action都没有用,太不专业了。在上传附件或图片的时候写action上传不了居然还将web.xml中的<url-pattern>/*</url-pattern>换为:<url-pattern>*.action</url-pattern>这样以来势必会影响到其他地方。本文主要讲解插件的详细制作过程以及问题的处理,均为结合Struts2的标准方式,绝无什么水货处理方式!
KindEditor官方:http://www./
KindEditor4.0测试版Demo:http://www./ke4/php/demo.php
注意:KindEditor官方4.0下月发布正式版,已经有了代码高亮、附件上传等插件,如果你能等的话就暂扫一下我的文章就可以了!!!
KindEditor插件之图片上传
第一步是什么呢?当然是参考官方的图片上传DEMO!
在下载的包中找到jsp/demo.jsp打开看下源码,直接粘到你的页面中吧!注意js,css等路径就行了。fileManager这个是浏览远程图片的,基本没人用这个吧?没什么意义,所以关掉吧!
看下我的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 | <%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www./TR/xhtml1/DTD/xhtml1-transitional.dtd"> < head > < head > < base href="<%=basePath%>"> < title >KindEditor示例</ title > < link rel = "shortcut icon" type = "image/x-icon" href = "./favicon.png" /> < meta http-equiv = "Content-Type" content = "text/html; charset=utf-8" /> < meta http-equiv = "pragma" content = "no-cache" > < meta http-equiv = "cache-control" content = "no-cache" > < meta http-equiv = "expires" content = "0" > < script src="<%=basePath%>js/jquery.js" type="text/javascript"></ script > < script src="<%=basePath%>js/kindeditor.js" type="text/javascript"></ script > < script type = 'text/javascript' > <!-- $(document).ready(function(){ KE.show({ id : 'content', resizeMode : 1, shadowMode : false, allowPreviewEmoticons : false, allowUpload : true, syncType : 'auto', urlType : 'domain', cssPath : 'css/ke.css', imageUploadJson : '<%=basePath%>fileUpDown/onUploadImg.do', items : [ 'bold', 'italic', 'underline', 'strikethrough', 'removeformat', '|', 'insertorderedlist', 'insertunorderedlist', '|', 'textcolor', 'bgcolor', 'fontname', 'fontsize', '|', 'link', 'unlink', 'emoticons', 'code', 'image', 'flash', 'quote', 'attach', '|', 'selectall', 'source', 'about' ], afterCreate : function(id) { KE.event.ctrl(document, 13, function() { if(KE.isEmpty('content')){ alert('文章为空'); }else{ KE.util.setData(id); document.forms['editform'].submit(); } }); KE.event.ctrl(KE.g[id].iframeDoc, 13, function() { if(KE.isEmpty('content')){ alert('文章为空'); }else{ KE.util.setData(id); document.forms['editform'].submit(); } }); } }); }); var check={ form_submit:function(){ if(KE.isEmpty('content')){ alert('文章为空'); return false; }else{ return true; } } }; //--> </ script > </ head > < body > < form id = "editform" name = "editform" action = "article/showDemo_DemoEditContent.do" method = "post" onsubmit = "return check.form_submit();" > < textarea id = "content" name = "content" style = "width: 580px; height: 250px; visibility: hidden;" ></ textarea > < br /> 您当前输入了 < span id = "word_count1" >0</ span > 个文字。(字数统计包含HTML代码。) < br /> 您当前输入了 < span id = "word_count2" >0</ span > 个文字。(字数统计包含纯文本、IMG、EMBED,不包含换行符,IMG和EMBED算一个文字。) < br /> < button id = "id_submit" > 提交 </ button >(提交快捷键: Ctrl + Enter) < br /> < input type = "button" name = "button" value = "取得HTML" onclick = "javascript:alert(KE.html('content'));" /> < input type = "button" name = "button" value = "判断是否为空" onclick = "javascript:alert(KE.isEmpty('content'));" /> < input type = "button" name = "button" value = "取得文本" onclick = "javascript:alert(KE.text('content'));" /> < input type = "button" name = "button" value = "取得文本(包含img,embed)" onclick = "javascript:alert(KE.util.getPureData('content'));" /> < input type = "button" name = "button" value = "取得选中HTML" onclick = "javascript:alert(KE.selectedHtml('content'));" /> < br /> < br /> < input type = "button" name = "button" value = "设置HTML" onclick="javascript:KE.html('content', '<h3>Hello KindEditor</ h3 >');" /> < input type = "button" name = "button" value = "设置文本" onclick="javascript:KE.text('content', '<h3>Hello KindEditor</ h3 >');" /> < input type = "button" name = "button" value = "插入HTML" onclick="javascript:KE.insertHtml('content', '<strong>测试内容</ strong >');" /> < input type = "button" name = "button" value = "添加HTML" onclick="javascript:KE.appendHtml('content', '<strong>Append HTML</ strong >');" /> < input type = "button" name = "button" value = "清空内容" onclick = "javascript:KE.html('content', '');" /> </ form > </ body > </ html > |
imageUploadJson的参数action这个我们还没有写呢!不要着急,如果你急的已经部署打开了该页面你会发现缺了三个图标,那是我们以后文章中实实在在写的三个插件的图标。
cssPath : 'css/ke.css' 这个是编辑器内容里的一些自定义的样式,比如我们要写引用文本插件,代码高亮插件的时候就用得着了!暂时别急,写上了就写上了也没什么问题。我们稍后完成!
第二步写我们的重中之重的action:
首先声明下我访问action的时候结尾不是以action结尾的,我是以do结尾的(你喜欢什么就配什么,改不改无所谓!菜鸟别纠结这个问题),在struts中怎么配置为.do结尾滴呢?
顺便给菜鸟补下课:
在src根目录下创建struts.properties文件,内容为:struts.action.extension=do即可大功告成!!!哇哈哈,简单嘛?
然后参考解压包jsp/upload_json.jsp,接下来我们要将其转换成action
第一步直接写类吧:
怎么写?为什么有人说拿不到request的任何参数?还说是KindEditor或Struts2的Bug?污蔑!纯属污蔑,误人子弟的人们最可恨!
废话下:struts2对文件上传进行了包装,也就是说你可以直接拿到页面中的file!不需要像写Servlet那样写了!
好直接复制upload_json.jsp的代码到action中吧?然后改改?
我们要记得在struts2中action获取文件的时候: 页面<input type="file" name="imgFile">(哪里来的这个?参看你下载官方压缩包中的:plugins\image\image.html)
那么action类属性就应当为:
1 private File imgFile; 2 /** 3 * 文件名称 4 */ 5 private String imgFileFileName; 6 7 /** 8 * 图片宽度 9 */10 private String imgWidth; 11 12 /**13 * 图片高度 14 */15 private String imgHeight; 16 17 /**18 * 图片对齐方式 19 */20 private String align; 21 22 /**23 * 图片标题 24 */25 private String imgTitle;
其他的属性还是和原来action中的写法一样,哪里不一样呢?再给菜鸟补下课:
取文件名的话你的属性要这么写:页面file对象的name+FileName
取文件类型的话你的属性要这么写:页面file对象的name+ContentType
别忘了你的getter\setter方法!!!要不然你真死了都拿不到值!(纯属废话,我咋那么多废话?)
action的具体方法请看:
1 public String uploadImg() { 2 3 response.setContentType("text/html; charset=UTF-8"); 4 // 文件保存目录路径 5 String savePath = ServletActionContext.getServletContext().getRealPath("/") +"attached/"; 6 // 文件保存目录URL 7 String saveUrl = request.getContextPath() +"/attached/"; 8 // 定义允许上传的文件扩展名 9 String[] fileTypes =new String[] { "gif", "jpg", "jpeg", "png", "bmp" }; 10 // 最大文件大小11 long maxSize = getMaxSize(Constant.FILE_SIZE_IMG); 12 PrintWriter out =null; 13 try { 14 out = response.getWriter(); 15 } catch (IOException e1) { 16 log.error(e1); 17 } 18 19 if (imgFile ==null) { 20 out.println(getError("请选择文件。")); 21 returnnull; 22 } 23 24 // 检查目录25 File uploadDir =new File(savePath); 26 if (!uploadDir.isDirectory()) { 27 out.println(getError("上传目录不存在。")); 28 returnnull; 29 } 30 // 检查目录写权限31 if (!uploadDir.canWrite()) { 32 out.println(getError("上传目录没有写权限。")); 33 returnnull; 34 } 35 // 创建文件夹36 SimpleDateFormat sdf =new SimpleDateFormat("yyyyMMdd"); 37 String ymd = sdf.format(new Date()); 38 savePath += ymd +"/"; 39 saveUrl += ymd +"/"; 40 File dirFile =new File(savePath); 41 if (!dirFile.exists()) { 42 dirFile.mkdirs(); 43 } 44 String fileExt = imgFileFileName.substring(imgFileFileName.lastIndexOf(".") +1).toLowerCase(); 45 if (!Arrays.<String> asList(fileTypes).contains(fileExt)) { 46 out.println(getError("上传文件扩展名["+ fileExt +"]是不允许的扩展名。")); 47 returnnull; 48 } 49 if (imgFile.length() > maxSize) { 50 out.println(getError("[ "+ imgFileFileName +" ]超过单个文件大小限制,文件大小[ "+ imgFile.length() +" ],限制为[ "+ maxSize +" ] ")); 51 returnnull; 52 } 53 SimpleDateFormat df =new SimpleDateFormat("yyyyMMddHHmmss"); 54 String newFileName = df.format(new Date()) +"_"+new Random().nextInt(1000) +"."+ fileExt; 55 File uploadedFile =new File(savePath, newFileName); 56 try { 57 FileUtil.Copy(imgFile, uploadedFile); 58 JSONObject obj =new JSONObject(); 59 obj.put("error", 0); 60 obj.put("url", saveUrl + newFileName); 61 log.debug(obj); 62 out.println(obj.toString()); 63 log.debug("上传图片:["+ uploadedFile.getName() +"]"+">>>["+ newFileName +"]成功"); 64 } catch (IOException e) { 65 log.error("图片上传失败:"+ e); 66 } 67 returnnull; 68 } 69 private String getError(String message) { 70 JSONObject obj =new JSONObject(); 71 obj.put("error", 1); 72 obj.put("message", message); 73 log.debug(obj); 74 return obj.toString(); 75 }
然后你问我:getMaxSize(Constant.FILE_SIZE_IMG);哪来的,不好意思我有个配置文件里放的图片文件限制大小.
如果你想上传2M的文件那么就应当为:2*1024*1024
FileUtil.Copy(imgFile, uploadedFile);同理,就是个拷贝文件的方法而已没有什么大不同,这里还牵扯到文件上传的一个经典问题!
有人说临时文件没有删掉或struts报临时文件的错误.别急一会一起解决掉!
如果你写到这就着急的运行鸟,那么你伤心的看着404页面吧....
最后一步:配置struts
1.记得我们刚才改action的访问后缀了吗?继续在刚才的struts.properties中加入:
1 ### Parser to handle HTTP POST requests, encoded using the MIME-type multipart/form-data 2 # struts.multipart.parser=cos 3 # struts.multipart.parser=pell 4 struts.multipart.parser=jakarta 5 # uses javax.servlet.context.tempdir by default 6 struts.multipart.saveDir=c:\\temp 7 # -1 nolimit 8 struts.multipart.maxSize=-1
最后一个是上传文件大小,因为我们在action中配置的,所以这里就直接不限制了.默认2M
中间的是临时文件存放目录,我们随便配吧,默认空所以就跑到你的tomcat下了.
第一个...你想让我解释嘛?我X你!X完了就告诉你,那个是说你用什么组件来实现上传功能!支持commons-fileupload就是默认的jakarta,cos很出名,另一个偶土了没听说过.
然后我们忘了我们的action还没有配置呢!
<action name="onUploadImg" class="xxx.x.UploadAction" method="uploadImg"></action>
我直接指定method方法了...当然你也可以直接默认execute...随你,最基础的东西.