zoukankan      html  css  js  c++  java
  • CKEditor上传插件

    CKEditor上传插件


    前言


    CKEditor上传插件是不是免费的,与您分享在此开发。这个插件是基于ASP.NET MVC下开发的,假设是webform的用户或者其他语言的用户。能够參考把server端做对应的改动。看图:



    大家能够看到Browse Button和Upload选项卡。

    以下分步具体解释三部分的实现:浏览server端图片或文件。上传图片或文件,CKEditor配置。



    浏览server端图片或文件


    先上图:



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


    ASP.NET MVC中Controller中浏览页面的action代码例如以下(即页面相应的server端代码):

    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; 20%;height: 100%;padding: 5px;}
            section{ float: right;padding: 5px;margin-left: 10px;border: solid 3px #008b8b; 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 = match.Value; if (value.EndsWith("&")) return value.Substring(0, 1); else return string.Empty; } #endregion


    致此,“浏览server端图片或文件”部分就完毕了。


    上传图片或文件


    上图:





    (最后改动 2014/6/11)

    由于这个弹框是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又这么简单好用,功能强大,实在没有勇气放弃它而去选择其他的产品。

    自已从零開始开发一个富文该编辑器?重复-create家庭的车轮,很少有人愿意去做?我们希望帮助人们谁有需求,假设花钱,请顶一下,非常感谢~~








  • 相关阅读:
    hdu5608 function
    Codeforces Round #535 (Div. 3) 解题报告
    HDU4746 Mophues
    HDU5663 Hillan and the girl
    AtCoder Beginner Contest 117 解题报告
    GDOI2018D2T1 谈笑风生
    BZOJ4018: 小Q的幻想之乡
    牛客寒假算法基础集训营6 解题报告
    win32拖拽编程
    项目开发中的贝塞尔曲线
  • 原文地址:https://www.cnblogs.com/blfshiye/p/4583123.html
Copyright © 2011-2022 走看看