首页 > 代码库 > CKEditor上传插件

CKEditor上传插件

CKEditor上传插件


前言


CKEditor的上传插件不是免费的,特此开发一个与大家共享。此插件是基于ASP.NET MVC下开发的,如果是webform的用户或者其它语言的用户,可以参考把服务器端做相应的修改。看图:



大家可以看到Browse Button和Upload选项卡。下面分步详解三部分的实现:浏览服务器端图片或文件,上传图片或文件,CKEditor配置。


浏览服务器端图片或文件


先上图:



做了一个十分简易的浏览页面,左半部分是文件夹树,右半部分则显示当前文件夹中的图片。

ASP.NET MVC中Controller中浏览页面的action代码如下(即页面对应的服务器端代码):

public ActionResult Browse()
        {
            var type = Request.QueryString["Type"];
            var isImage = !string.IsNullOrEmpty(type) && type.Equals("Images", StringComparison.InvariantCultureIgnoreCase);
            ViewBag.IsImg = isImage;
            return View();
        }

不是ASP.NET MVC的用户,就把它当成是页面加载。
View(即页面代码)代码如下:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Browse</title>
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/modernizr")
    <link href="/SHTracker/Scripts/TreeView/jquery.treeview.css" rel="stylesheet" type="text/css" />
    <link href="/SHTracker/Scripts/TreeView/screen.css" rel="stylesheet" type="text/css" />
    <script src="/SHTracker/Scripts/TreeView/jquery.treeview.pack.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("body>aside>ul").treeview({
                animated: true,
                persist: "location",
                collapsed: true,
                unique: false
            });
        });
    </script>
    <style type="text/css">
        aside{ border: solid 3px #006400;float: left;width: 20%;height: 100%;padding: 5px;}
        section{ float: right;padding: 5px;margin-left: 10px;border: solid 3px #008b8b;width: 70%;height: 100%;}
        section ul li{ float: left;padding: 10px;list-style-type: none;}
        img{ z-index: 999;cursor: pointer;}
    </style>
</head>
<body>
    <aside>
        <ul>
            <li>Home</li>
            <ul>
                @if ((bool) ViewBag.IsImg)
                {
                    <li>Images
                        <ul>
                            @foreach (var dir in Directory.GetDirectories(Server.MapPath("/Images")))
                            {

                                <li><a href="@ICStars2_0.Common.UrlHelper.SafeAddQueryToURL("folderpath", Url.Encode(dir.Replace(Server.MapPath("/"), "")), Request.RawUrl)">@Path.GetFileName(dir)</a></li>
                            }
                        </ul>
                    </li>
                }
                else
                {
                    <li>Docs
                        <ul>
                            @foreach (var dir in Directory.GetDirectories(Server.MapPath("/Docs")))
                            {
                                <li><a href="@ICStars2_0.Common.UrlHelper.SafeAddQueryToURL("folderpath", Url.Encode(dir.Replace(Server.MapPath("/"), "")), Request.RawUrl)">@Path.GetFileName(dir)</a></li>
                            }
                        </ul>
                    </li>
                }
            </ul>
        </ul>
    </aside>
    <section>
        @if (!string.IsNullOrEmpty(Request.QueryString["folderpath"]))
        {
            <ul>
                @{ var imgTypes = new[] {".jpg", ".gif", ".png"}; }
                @foreach (var file in Directory.GetFiles(Server.MapPath("/" + Request.QueryString["folderpath"])))
                {
                    if ((bool) ViewBag.IsImg && imgTypes.Contains(Path.GetExtension(file.ToLower())))
                    {

                        <li><img src="/@Request.QueryString["folderpath"].Replace("\\", "/")/@Path.GetFileName(file)" width="100" onclick=" window.opener.CKEDITOR.tools.callFunction(@Request.QueryString["CKEditorFuncNum"], this.src);window.close(); "/></li>

                    }
                    else
                    {
                        <li><a href="javascript:" onclick=" window.opener.CKEDITOR.tools.callFunction(@Request.QueryString["CKEditorFuncNum"], ‘/@Request.QueryString["folderpath"].Replace("\\", "/")/@Path.GetFileName(file)‘);window.close(); ">@Path.GetFileName(file)</a></li>
                    }
                }
            
            </ul>
        }
    </section>
</body>
</html>

页面引用了JQUERY,树状菜单部分是jquery的treeview插件,可自行GOOGLE,也可留言,我email给你。
其中的ICStars2_0.Common.UrlHelper.SafeAddQueryToURL方法,其实是我比较懒了随便GOOGLE了一个使用,就是给URL添加参数。代码如下:

#region = SafeAddQueryToURL =
        /// <summary>
        /// Add a query to an URL.
        /// if the URL has not any query,then append the query key and value to it.
        /// if the URL has some queries, then check it if exists the query key already,replace the value, or append the key and value
        /// if the URL has any fragment, append fragments to the URL end.
        /// </summary>
        /// <example>
        ///             string s = "http://blog.csdn.net/leewhoee/?a=1&b=2&c=3#tag";
        /// WL(SafeRemoveQueryFromURL("a",s));
        /// WL(SafeRemoveQueryFromURL("b",s));
        /// WL(SafeRemoveQueryFromURL("c",s));
        /// WL(SafeAddQueryToURL("d","new",s));
        /// WL(SafeAddQueryToURL("a","newvalue",s));
        ///            输出如下:
        ///            http://blog.csdn.net/leewhoee/?b=2&c=3#tag
        ///            http://blog.csdn.net/leewhoee/?a=1&c=3#tag
        ///            http://blog.csdn.net/leewhoee/?a=1&b=2#tag
        ///            http://blog.csdn.net/leewhoee/?a=1&b=2&c=3&d=new#tag
        ///            http://blog.csdn.net/leewhoee/?a=newvalue&b=2&c=3#tag
        /// </example>
        public static string SafeAddQueryToURL(string key, string value, string url)
        {
            int fragPos = url.LastIndexOf("#");
            string fragment = string.Empty;
            if (fragPos > -1)
            {
                fragment = url.Substring(fragPos);
                url = url.Substring(0, fragPos);
            }
            int querystart = url.IndexOf("?");
            if (querystart < 0)
            {
                url += "?" + key + "=" + value;
            }
            else
            {
                Regex reg = new Regex(@"(?<=[&\?])" + key + @"=[^\s&#]*", RegexOptions.Compiled);
                if (reg.IsMatch(url))
                    url = reg.Replace(url, key + "=" + value);
                else
                    url += "&" + key + "=" + value;
            }
            return url + fragment;
        }
        #endregion

        #region = SafeRemoveQueryFromURL =
        /// <summary>
        /// Remove a query from url
        /// </summary>
        /// <param name="key"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string SafeRemoveQueryFromURL(string key, string url)
        {
            Regex reg = new Regex(@"[&\?]" + key + @"=[^\s&#]*&?", RegexOptions.Compiled);
            return reg.Replace(url, new MatchEvaluator(PutAwayGarbageFromURL));
        }
        private static string PutAwayGarbageFromURL(Match match)
        {
            string value = http://www.mamicode.com/match.Value;>
致此,“浏览服务器端图片或文件”部分就完成了。


上传图片或文件


上图:



因为这个弹框是CKEditor提供的,我们只需要处理请求。下面是处理WEB请求的ACTION(可以用任何语言处理些请求,逻辑上大体相同):

[HttpPost]
        public ActionResult FileUpload()
        {
            var ckEditorFuncNum = Request.QueryString["CKEditorFuncNum"];
            var type = Request.QueryString["Type"];
            var isImage = !string.IsNullOrEmpty(type) && type.Equals("Images", StringComparison.InvariantCultureIgnoreCase);
            var maxContentLength = isImage ? 512*1024 : 1024*1024;
            var file = Request.Files["upload"];
            if (file == null)
            {
                return Content("No file has been chosen!");
            }
            if (file.ContentLength > maxContentLength)
            {
                return Content("The image file size should be no bigger than 512KB! The document file size should be no bigger than 1024KB!");
            }
            var urlpath = string.Empty;
            var datestamp = DateTime.Now.ToString("MMddyyyy");
            var rootfolderpath = isImage ? "/Images/" : "/docs/";
            var folderpath = Server.MapPath(rootfolderpath) + datestamp;
            if (file.ContentLength > 0)
            {
                var filename = Path.GetFileNameWithoutExtension(file.FileName);
                var fileextension = Path.GetExtension(file.FileName);
                var timestamp = DateTime.Now.ToString("MMddyyyyHHmmssfff");
                var filepath = string.Format("{0}/{1}{2}{3}", folderpath, filename, timestamp,
                                                fileextension);
                urlpath = string.Format("{4}{0}/{1}{2}{3}", datestamp, filename, timestamp,
                                                fileextension, rootfolderpath);
                if (!Directory.Exists(folderpath))
                {
                    Directory.CreateDirectory(folderpath);
                }
                file.SaveAs(filepath);
            }
            return
                Content(
                    string.Format(
                        @"<script type=""text/javascript"">window.parent.CKEDITOR.tools.callFunction({0}, ""{1}"");</script>",
                        ckEditorFuncNum, urlpath));
        }

如果你不懂ASP.NET MVC,下面做一些简单的解释。[HttpPost]表明只处理POST请求,return Content("")是返回一个纯文本字符串,其它部分大同小异。唯一值得注意的是最后返回了一段javascript脚本给CKEditor,它促使窗口跳转到Image Info选项卡并把图片URL传递过去,然后预览。如下图:





图片或文件上传部分到这里为止,下面介绍怎么配置CKEditor。


CKEditor配置



CKEditor里有一个配置文件config.js,我们只需要设置几个链接就可以了。代码如下:

/**
 * @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
 * For licensing, see LICENSE.html or http://ckeditor.com/license
 */

CKEDITOR.editorConfig = function (config) {
    config.extraPlugins = "autogrow,imagebrowser,filebrowser";
    /*config autogrow*/
    config.autoGrow_maxHeight = 400;
    /*config autogrow end*/
    /*config imagebrowser*/
    //config.imageBrowser_listUrl = "";
    /*config imagebrowser end*/

    /*config filebrowser*/
    config.filebrowserImageBrowseUrl = ‘/SHTracker/CKEditor/Browse?type=Images‘;
    config.filebrowserImageUploadUrl = ‘/SHTracker/CKEditor/FileUpload?type=Images‘;
    config.filebrowserBrowseUrl = ‘/SHTracker/CKEditor/Browse?type=docs‘;
    config.filebrowserUploadUrl = ‘/SHTracker/CKEditor/FileUpload?type=docs‘;
    config.filebrowserImageWindowWidth = 640;
    config.filebrowserImageWindowHeight = 480;
    /*config filebrowser end*/
    // Define changes to default configuration here. For example:
    // config.language = ‘fr‘;
    // config.uiColor = ‘#AADC6E‘;
    config.skin = ‘Moono‘;
    config.disableNativeSpellChecker = false;
};

extraPlugins里设置了imagebrowser图片浏览和filebrowser文件浏览。然后为其配置处理请求的URL:
config.filebrowserImageBrowseUrl = ‘/SHTracker/CKEditor/Browse?type=Images‘;
    config.filebrowserImageUploadUrl = ‘/SHTracker/CKEditor/FileUpload?type=Images‘;
    config.filebrowserBrowseUrl = ‘/SHTracker/CKEditor/Browse?type=docs‘;
    config.filebrowserUploadUrl = ‘/SHTracker/CKEditor/FileUpload?type=docs‘;

请确保你的URL可以正确访问。此时,这个CKEditor的文件图片上传插件就完成了。


总结


相信不愿意花钱买CKEditor插件的朋友一定用的上此功能。对于一个富文本编辑器,怎么能没有文件图片上传功能呢?CKEditor又这么简单好用,功能强大,实在没有勇气放弃它而去选择其它的产品。自已从零开始开发一个富文本编辑器?重复造轮子的活儿没有几个人愿意干吧?希望能帮到有需要的人,如果用上了请顶一下吧,特此感谢~~