码迷,mamicode.com
首页 > 其他好文 > 详细

kindeditor添加插件

时间:2014-11-25 00:01:38      阅读:377      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   使用   sp   

   KindEditor是一套开源的HTML可视化编辑器,主要用于让用户在网站上获得所见即所得编辑效果。说实话在使用这个编辑器以前,我也使用过别的编辑器,最后不是因为使用麻烦,就是因为程序太臃肿,而放弃使用,可是KindEditor不同,不仅结构小巧,而且功能强大,最主要的是它采用插件的开发管理方式,能很容易再它的基础上添加插件来实现自己的功能

   本人在使用KindEditor过程中,随着使用时间的加长,发现KindEditor一个最大的缺陷,那就是不支持文件的上传,所以到网上搜了很多相关的资料,发现可以自己加插件到KindEditor中,现整理方法如下:

一.打开kindeditor.js文件

   1.找到KE.lang,如下图所示:

bubuko.com,布布扣
在里面加入以下语句:

accessory : ‘插入附件‘,

invalidAccessory : "请输入有效的URL地址。只允许rar,zip格式。",

 

bubuko.com,布布扣

bubuko.com,布布扣

  2.在KE.setting中加入将该功能加入到kindeditor中,加入后的截图如下:

bubuko.com,布布扣


二、经过第一步后,准备工作已经作完了,下面就是编写有关上传附件的核心代码,将以下的代码加入到kindeditor.js文件中,加入到该文件的最后    })(KindEditor);之前 及上一个“;”之后即可

KE.plugin[‘accessory‘] = {
     click : function (id) {
         KE.util.selection(id);
         this.dialog = new KE.dialog({
             id : id,
             cmd : ‘accessory‘,
             file : ‘accessory.html‘,
             width : 310,
             height : 55,
             loadingMode : true,
             title : KE.lang[‘accessory‘],
             yesButton : KE.lang[‘yes‘],
             noButton: KE.lang[‘no‘]
         });
         this.dialog.show();
     },
     check: function (id) {
         var dialogDoc = KE.util.getIframeDoc(this.dialog.iframe);
         var url = KE.$(‘accessoryFile‘, dialogDoc).value;
         if (url.match(/\.(rar|zip)$/i) == null) {
             alert(KE.lang[‘invalidAccessory‘]);
             window.focus();
             KE.g[id].yesButton.focus();
             return false;
         }
         return true;
     },
     exec : function (id) {
         var self = this;
         var dialogDoc = KE.util.getIframeDoc(this.dialog.iframe);
         if (!this.check(id)) return false;
         KE.$(‘editorId‘, dialogDoc).value = id;
   var uploadIframe = KE.$(‘uploadIframe‘, dialogDoc);
   KE.util.showLoadingPage(id);
 
         var onloadFunc = function() {
             KE.event.remove(uploadIframe, ‘load‘, onloadFunc);
             KE.util.hideLoadingPage(id);
             var uploadDoc = KE.util.getIframeDoc(uploadIframe);
             var data = ‘‘;
             try {
                 data = KE.util.parseJson(uploadDoc.body.innerHTML);
             } catch(e) { alert(KE.lang.invalidJson); }
             if (typeof data === ‘object‘ && ‘error‘ in data) {
                 if (data.error === 0) {
                     self.insert(id, data.url,data.filename);
                 } else {
                     alert(data.message);
                     return false;
                 }
             }
         };
 
         KE.event.add(uploadIframe, ‘load‘, onloadFunc);
         dialogDoc.uploadForm.submit();
 
         return;
     },
     insert : function (id, url, filename) {
         KE.util.insertHtml(id, ‘<a href="‘ + url + ‘" >‘+filename+‘</a>‘);
         this.dialog.hide();
         KE.util.focus(id);
     }
 };

注意最后的分号

三、在plugins文件夹中增加上传附件的文件,文件名为accessory.html,这个名字可以在以上的代码中修改(修改以上代码中的红色部分,即可)

<!doctype html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <title>Accessory</title>
        <style type="text/css">
            body { font-size: 12px; margin: 0px; background: #F0F0EE; overflow: hidden; }
        </style>
        <script type="text/javascript">
            var KE = parent.KindEditor;
            location.href.match(/\?id=([\w-]+)/i);
            var id = RegExp.$1;
            KE.event.ready(function () { KE.util.hideLoadingPage(id); }, window, document);
        </script>
    </head>
    <body>
        <iframe name="uploadIframe" id="uploadIframe" style="display:none;"></iframe>
        <form name="uploadForm" method="post" enctype="multipart/form-data" action="upload.jsp"target="uploadIframe">
            <input type="hidden" id="editorId" name="id" value="" />
                <table border="0" cellpadding="0" cellspacing="0" align="center">
                  <tr><td><input type="file" id="accessoryFile" name="accessoryFile" style="width:220px;" /></td></tr>
                </table>
        </form>
    </body>
</html>

四、编写附件上传的处理页面,这里使用jsp进行编写,以上的红色部分,即是要提交到的处理页面,这里upload.jsp和accessory.html在一个文件夹下,大家也可以放到别的文件夹下,然后改一下上面代码的action值就可以了,upload.jsp内容如下:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.*,java.io.*" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.disk.*" %>
<%@ page import="org.apache.commons.fileupload.servlet.*" %>
<%@ page import="org.json.simple.*" %>
<%

//文件保存目录路径
String savePath = pageContext.getServletContext().getRealPath("/") + "attached/";
//文件保存目录URL
String saveUrl  = request.getContextPath() + "/attached/";
//定义允许上传的文件扩展名
String[] fileTypes = new String[]{"rar", "zip"};
//最大文件大小
long maxSize = 1000000;

response.setContentType("text/html; charset=UTF-8");

if(!ServletFileUpload.isMultipartContent(request)){
 out.println(getError("请选择文件。"));
 return;
}
//检查目录
File uploadDir = new File(savePath);
if(!uploadDir.isDirectory()){
 out.println(getError("上传目录不存在。"));
 return;
}
//检查目录写权限
if(!uploadDir.canWrite()){
 out.println(getError("上传目录没有写权限。"));
 return;
}

FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
 FileItem item = (FileItem) itr.next();
 String fileName = item.getName();
 long fileSize = item.getSize();
 if (!item.isFormField()) {
  //检查文件大小
  if(item.getSize() > maxSize){
   out.println(getError("上传文件大小超过限制。"));
   return;
  }
  //检查扩展名
  String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
  if(!Arrays.<String>asList(fileTypes).contains(fileExt)){
   out.println(getError("上传文件扩展名是不允许的扩展名。"));
   return;
  }
  SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
  String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
  try{
   File uploadedFile = new File(savePath, newFileName);
   item.write(uploadedFile);
  }catch(Exception e){
   out.println(getError("上传文件失败。"));
   return;
  }

  JSONObject obj = new JSONObject();
  obj.put("error", 0);
  obj.put("url", saveUrl + newFileName);
  obj.put("filename",fileName);
  out.println(obj.toJSONString());
 }
}
%>
<%!
private String getError(String message) {
 JSONObject obj = new JSONObject();
 obj.put("error", 1);
 obj.put("message", message);
 return obj.toJSONString();
}
%>

五、修改skins目录里的default.gif,增加附件图标,可采用photoshop等图片处理软件,在default.gif的最后面加一个附件图标,大小为16*16px的即可

bubuko.com,布布扣

六、修改skins目录里的default.css,加入

.ke-icon-accessory
{
    background-position: 0px -960px;
    width: 16px;
    height: 16px;
}

七、测试效果如下:

bubuko.com,布布扣

八、完成

 

 

转自:http://blog.sina.com.cn/s/blog_7b62c61c0100um3z.html

kindeditor添加插件

标签:style   blog   http   io   ar   color   os   使用   sp   

原文地址:http://www.cnblogs.com/maguoyong/p/4119808.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!