Kiven

Knowledge Has No Limit And Stick To It All The Time !
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

给KindEditor添加附件 整理笔记

Posted on 2011-11-07 17:04  KivenRo  阅读(12098)  评论(0编辑  收藏  举报

      想在编辑器中能够上传附件,但下载的编辑器一般都不带有附件上传的功能。在网上找了一些资料,发现用KindEditor可以添加附件,于是自己做了一个小DEMO,结果成功了。现在我把这个功能分享给各位园友,望各位多多指教。。。

 具体操作如下:

(一)首先修改 KindEditor 中的 kindeditor.js 文件:

1. 在脚本文件中的 items (有的js文件中显示的是 defaultItems )标识集合中加入 'accessory' (含单引号)。作为编辑器显示功能按钮的标识。

 

2. 找到 KE.lang 样式(格式)集合,在其中加入 accessory: '插入附件', 。

 

3. 同样在 KE.lang 样式(格式)集合中,加入对附件格式的限制说明:

invalidAccessory: "请上传有效的文件,只允许doc,xls,pdf,docx,xlsx,pptx,txt,ppt,rar,zip格式;\n或输入有效的URL地址。", 

 

4. 在 function(KE, undefined) 中添加附件的plugin插件:

 

KE.plugin['accessory'] = {
        click: function(id) {
            KE.util.selection(id);
            var dialog = new KE.dialog({
                id: id,
                cmd: 'accessory',
                width: 310,
                height: 90,
                title: KE.lang['accessory'],
                yesButton: KE.lang['yes'],
                noButton: KE.lang['no']
            });
            dialog.show();
        },
        check: function(id) {
            var dialogDoc = KE.util.getIframeDoc(KE.g[id].dialog);
            var type = KE.$('type', dialogDoc).value;
            var url = '';
            if (type == 1) {
                url = KE.$('imgFile', dialogDoc).value;
            } else {
                url = KE.$('url', dialogDoc).value;
            }

            if (url.match(/\.(doc|xls|ppt|pdf|txt|rar|zip)$/i) == null) {
                alert(KE.lang['invalidAccessory']);
                window.focus();
                KE.g[id].yesButton.focus();
                return false;
            }
            return true;
        },
        exec: function(id) {
            KE.util.select(id);
            var dialogDoc = KE.util.getIframeDoc(KE.g[id].dialog);
            var type = KE.$('type', dialogDoc).value;
            if (!this.check(id)) return false;
            if (type == 1) {
                KE.$('editorId', dialogDoc).value = id;
                dialogDoc.uploadForm.submit();
                return false;
            } else {
                var url = KE.$('url', dialogDoc).value;
                var title = KE.$('imgTitle', dialogDoc).value;

                this.insert(id, url, title, ext);
            }
        },
        insert: function(id, url, title, ext) {
            var img;
            g = KE.g[id];
            path = g.pluginsPath + 'accessory/';
            ; switch (ext) {
                case "doc":
                    // img = path + "doc.jpg";
                    img = "http://www.cnblogs.com/kindeditor/plugins/accessory/doc.jpg";
                    break;
                case "xls":
                    img = "http://www.cnblogs.com/kindeditor/plugins/accessory/xls.jpg";
                    break;
                case "ppt":
                    img = "http://www.cnblogs.com/kindeditor/plugins/accessory/ppt.jpg";
                    break;
                case "rar":
                    img = "http://www.cnblogs.com/kindeditor/plugins/accessory/rar.jpg";
                    break;
                case "zip":
                    img = "http://www.cnblogs.com/kindeditor/plugins/accessory/zip.jpg";
                    break;
                case "txt":
                    img = "http://www.cnblogs.com/kindeditor/plugins/accessory/txt.jpg";
                    break;
                case "pdf":
                    img = "http://www.cnblogs.com/kindeditor/plugins/accessory/pdf.jpg";
                    break;
                default:
                    img = "http://www.cnblogs.com/kindeditor/plugins/accessory/else.jpg";
            }
            var html = '<img src="' + img + '" >&nbsp;';
            html += '<a href="' + url + '" >';
            if (title) html += title;
            html += '</a>';
            alert(html)
            KE.util.insertHtml(id, html);
            KE.layout.hide(id);
            KE.util.focus(id);
        }

     };

 

5.在plugins文件夹中增加上传附件的文件 [文件名:accessory.html] ,文件源代码如下:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Accessory</title>
<style type="text/css" rel="stylesheet">
    body {
    font-size:12px;
    margin: 0px;
    background-color:#F0F0EE;
    overflow: hidden;
    }
    td.left1 {
    font-size:12px;
    width: 50px;
    padding: 2px;
    }
    td.right1 {
    font-size:12px;
    padding: 2px;
    }
    td.left2 {
    font-size:12px;
    width: 35px;
    padding: 2px;
    }
    td.right2 {
    font-size:12px;
    padding: 2px;
    width: 50px;
    }
</style>
<script type="text/javascript">
    function changeType(obj) {
        var url = document.getElementById('url');
        var imgFile = document.getElementById('imgFile');
        var trRemark = document.getElementById('trRemark');
        if (obj.value == 1) { //本地上传附件
            url.style.display = 'none';
            imgFile.style.display = 'block';
            trRemark.style.display = 'none';
        } else {
            url.style.display = 'block';
            imgFile.style.display = 'none';
            trRemark.style.display = 'block';
        }
    }
</script>
</head>
<body>
<form name="uploadForm" method="post" enctype="multipart/form-data" action="../asp.net/accessory_upload_json.ashx">
    <input type="hidden" id="editorId" name="id" value="" />
    <table border="0" cellpadding="0" cellspacing="0">
      <tr>
        <td class="left1">
          <select id="type" name="type" onchange="changeType(this);">
              <option value="1" selected="selected">本地</option>
              <option value="2">远程</option>
          </select>
        </td>
        <td class="right1">
          <input type="file" id="imgFile" name="imgFile" style="width:220px;" />
          <input type="text" id="url" name="url" value="http://" maxlength="255" style="width:220px;display:none;" />
        </td>
      </tr>
      <tr id="trRemark" style="display:none;">
        <td class="left1" align="right">说明:</td>
        <td class="right1"><input type="text" id="imgTitle" name="imgTitle" value="附件" maxlength="100" style="width:220px;" /></td>
      </tr>
    </table>
</form>
</body>
</html>

 

6.在 asp.net 文件夹中增加上传附件执行文件 [文件名:accessory_upload_json.ashx ],文件源代码如下:


<%@ WebHandler Language="C#" class="accessory" %>

/**
 * KindEditor ASP.NET
 * 功能:[插入附件] yx 2011.01.18
 * 本ASP.NET程序是演示程序,建议不要直接在实际项目中使用。
 * 如果您确定直接使用本程序,使用之前请仔细确认相关安全设置。
 */

using System;
using System.Collections;
using System.Web;
using System.IO;
using System.Globalization;
using LitJson;

public class accessory : IHttpHandler
{
    //文件保存目录路径
    private String savePath = "http://www.cnblogs.com/Uploads/accessory/"; //这里给自己想要保存文件的相对路径
    //定义允许上传的文件扩展名,docx,xlsx,pptx为office 2007以上的格式
    private String fileTypes = "doc,xls,ppt,docx,xlsx,pptx,pdf,txt,rar,zip";
    //最大文件不能超过5M
    private int maxSize = 5242880;

    private HttpContext context;

    public void ProcessRequest(HttpContext context)
    {
        this.context = context;

        HttpPostedFile imgFile = context.Request.Files["imgFile"];
        if (imgFile == null)
            showError("请选择文件。");

        String myYearDir = DateTime.Now.ToString("yyyy"); //保存文件的年份文件夹名称
        String myMonthDir = DateTime.Now.ToString("MM");  //保存文件的月份文件夹名称
        String dirPath = savePath + myYearDir + "/";
        if (!Directory.Exists(context.Server.MapPath(dirPath)))
            Directory.CreateDirectory(context.Server.MapPath(dirPath));//如果不存在该文件夹,则创建年份文件夹

        dirPath = dirPath + myMonthDir + "/";
        if (!Directory.Exists(context.Server.MapPath(dirPath)))
            Directory.CreateDirectory(context.Server.MapPath(dirPath));//如果不存在该文件夹,则创建月份文件夹

        String fileName = imgFile.FileName;
        String fileExt = Path.GetExtension(fileName).ToLower();
        ArrayList fileTypeList = ArrayList.Adapter(fileTypes.Split(','));

        if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
            showError("上传文件大小不能超过5M。");

        if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1)
            showError("上传文件扩展名是不允许的扩展名。");

        String newFileName = DateTime.Now.ToString("yyyyMMdd_HHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
        String filePath = context.Server.MapPath(dirPath) + newFileName;

        try
        {
            imgFile.SaveAs(filePath);
        }
        catch (Exception ex)
        {
            showError("保存附件出错。");
        }

        String fileUrl = dirPath + newFileName;

        //Hashtable hash = new Hashtable();
        //hash["error"] = 0; //上传成功
        //hash["url"] = fileUrl;
        //context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
        //context.Response.Write(JsonMapper.ToJson(hash));
        //context.Response.End();

        //////////////////////////////////////////////////////////////////////////////////////////////////
        // 插入附件到kindeditor中
        string id = context.Request["id"].Trim();           //kindeditor控件的id
        string url = fileUrl.Trim();                        //保存文件的相对路径
        string title = Path.GetFileName(fileName).Trim();   //文件名称(原名陈)
        string ext = fileExt.Substring(1).ToLower().Trim(); //文件后缀名
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append("<html>");
        sb.Append("<head>");
        sb.Append("<title>Insert Accessory</title>");
        sb.Append("<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">");
        sb.Append("</head>");
        sb.Append("<body>");
        //sb.Append("<script type=\"text/javascript\">parent.KE.plugin[\"accessory\"].insert(\"" + id + "\", \"" + url + "\",\"" + title + "\",\"" + ext + "\");</script>");
        sb.Append("<script type=\"text/javascript\">parent.KE.plugin[\"accessory\"].insert(\"" + id + "\", \"" + url + "\",\"" + title + "\",\"" + ext + "\");</script>");
        sb.Append("</body>");
        sb.Append("</html>");
      //  context.Response.Write(sb.ToString());
        context.Response.End();
    }

    private void showError(string message)
    {
        Hashtable hash = new Hashtable();
        hash["error"] = 1; //上传错误
        hash["message"] = message;
        context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
        context.Response.Write(JsonMapper.ToJson(hash));
        context.Response.End();
    }

    public bool IsReusable
    {
        get
        {
            return true;
        }
    }
}

 

7. 修改 skins/default 文件夹中的 default.gif 文件,加入上传附件的图标,(这里DEMO中的图为例,可修改)

 

 

8. 在 skins 文件夹中的 default.css 文件中添加以下代码:

 

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

 

演示图:

 

 

 

 

 

 

 

 

到此,就修改完成了。如果有更好的修改方法或提议,就一同分享一下吧!!!