程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> CKEditor上傳插件

CKEditor上傳插件

編輯:C++入門知識

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;
}





    
    Browse
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/modernizr")
    
    
    <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>
    


    
        
  • Home
    • @if ((bool) ViewBag.IsImg) {
    • Images
        @foreach (var dir in Directory.GetDirectories(Server.MapPath("/Images"))) {
      • @Path.GetFileName(dir)
      • }
    • } else {
    • Docs
        @foreach (var dir in Directory.GetDirectories(Server.MapPath("/Docs"))) {
      • @Path.GetFileName(dir)
      • }
    • }
@if (!string.IsNullOrEmpty(Request.QueryString["folderpath"])) {
    @{ 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()))) {
  • } else {
  • @Path.GetFileName(file)
  • } }
}

頁面引用了JQUERY,樹狀菜單部分是jquery的treeview插件,可自行GOOGLE,也可留言,我email給你。 其中的ICStars2_0.Common.UrlHelper.SafeAddQueryToURL方法,其實是我比較懶了隨便GOOGLE了一個使用,就是給URL添加參數。代碼如下:
#region = SafeAddQueryToURL =
        /// 
        /// 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.
        /// 
        /// 
        ///             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
        /// 
        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 =
        /// 
        /// Remove a query from url
        /// 
        /// 
        /// 
        /// 
        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

致此,“浏覽服務器端圖片或文件”部分就完成了。

上傳圖片或文件


上圖:
\

因為這個彈框是CKEditZ喎?http://www.Bkjia.com/kf/ware/vc/" target="_blank" class="keylink">vcszhuam1xKOsztLDx9a70OjSqrSmwO3H68fzoaPPwsPmyse0psDtV0VCx+vH87XEQUNUSU9OKL/J0tTTw8jOus7T79HUtKbA7dCpx+vH86Oswt+8rcnPtPPM5c/gzawpo7oKPGJyPgoKPHByZSBjbGFzcz0="brush:java;">[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又這麼簡單好用,功能強大,實在沒有勇氣放棄它而去選擇其它的產品。自已從零開始開發一個富文本編輯器?重復造輪子的活兒沒有幾個人願意干吧?希望能幫到有需要的人,如果用上了請頂一下吧,特此感謝~~






  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved