CKEditor upload plug-in

Source: Internet
Author: User

CKEditor upload plug-in
Preface
The CKEditor upload plug-in is not free of charge. We hereby develop a plug-in for sharing with you. This plug-in is developed based on ASP. net mvc. If it is a webform user or a user in other languages, you can refer to modify the server. Figure:


You can see the Browse Button and Upload tabs. The following is a step-by-step explanation of the implementation of three parts: browsing images or files on the server side, uploading images or files, and CKEditor configuration.

Browse server images or files
First:


A simple page is displayed. The left half is the folder tree, and the right half is the picture in the current folder.
The action code of the browser page in ASP. net mvc Controller is as follows (that is, the server-side code of the page ):

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

Users who are not ASP. net mvc regard it as page loading. The View (page code) code is as follows:
@{    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)
  • } }
}

The page references JQUERY. The tree menu part is the jquery treeview plug-in. You can GOOGLE it or leave a message. I will email you. Among them, the ICStars2_0.Common.UrlHelper.SafeAddQueryToURL method is actually a lazy use by GOOGLE, that is, adding parameters to the URL. The Code is as follows:
# 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 )); /// output is as follows: // 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

As a result, the "browsing server images or files" section is complete.

Upload images or files
:


Because the bullet box is CKEditZ success? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> combined + vH87XEQUNUSU9OKL/j0tttw8jous7t79hukba7dcpx + vH86Oswt + 8rcnPtPPM5c/digest =" 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 shocould be no bigger than 512KB! The document file size shocould 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 = str Ing. 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 ));}
If you do not understand ASP. net mvc, the following is a simple explanation. [HttpPost] indicates that only POST requests are processed. return Content ("") returns a plain text string, and other parts are similar. The only thing worth noting is that a javascript script is returned to CKEditor, prompting the window to jump to the Image Info tab, passing the Image URL to the past, and then previewing. For example:




The following describes how to configure CKEditor.

CKEditor Configuration

CKEditor has a config. js configuration file. We only need to set several links. The Code is as follows:
/** * @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;};

In extraPlugins, imagebrowser Image Browsing and filebrowser file browsing are set. Then configure the URL for processing the request:
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';

Make sure that your URL can be accessed correctly. Now, the file Image Upload plug-in of CKEditor is complete.

Summary
I believe that friends who do not want to spend money to buy the CKEditor plug-in must use this function. For a rich text editor, how can I not upload file images? CKEditor is so easy to use and has powerful functions that it has no courage to choose other products. How can I develop a Rich Text Editor from scratch? Few people are willing to do repetitive wheel-building work? I hope you can help people who need it. If you have used it, please try it out. Thank you ~~






Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.