Kindeditor Extended paste Image function & Modify image upload path and upload image to image server via Webapi

Source: Internet
Author: User
Tags httpcontext tojson

Objective

Kindeditor is a very useful rich text editor, it's simple to use I will no longer introduce. But kindeditor the picture processing is not ideal.

There are two issues to be addressed in this blog post:

    • Kindeditor Extended Paste Image feature
    • Kindeditor Modify image upload path and upload image to Image server via WEBAPI (distributed image support)
Results Demo

1. Extended Paste Image Function Demo

2. Edit Image Upload Path Demo:

Our website demo address is: http://localhost:9393/

Our image server address is: http://localhost:9394/

We can see that the image is uploaded directly to the image server. At the same time we can configure whether the image upload to local or image server.

Expansion scenarios

1. Paste Image Feature Extension

For details, please refer to: http://www.cnblogs.com/cztisthebest/p/5913353.html

2. Modify image upload path and upload image to image server function extension via Webapi

First step: Referencing LitJSON.dll

Because the development language I'm using is c#&asp.net MVC. So first you need to reference LitJSON.dll in your project, such as:

Step Two: Modify the upload file: upload_json.ashx

<%@ WebHandler language="C #"class="Upload"%>/** * Kindeditor ASP. * This ASP. NET program is a demo program and is not recommended to be used directly in the actual project. * If you are sure to use this program directly, please carefully confirm the relevant safety settings before use. * */usingSystem;usingSystem.Collections;usingsystem.web;usingSystem.IO;usingSystem.Globalization;usingLitjson; Public classupload:ihttphandler{PrivateHttpContext context;  Public voidProcessRequest (HttpContext context) {//define the file extensions that are allowed to be uploadedHashtable exttable =NewHashtable (); Exttable.add ("Image","gif,jpg,jpeg,png,bmp"); Exttable.add ("Flash","swf,flv"); Exttable.add ("Media","SWF,FLV,MP3,WAV,WMA,WMV,MID,AVI,MPG,ASF,RM,RMVB"); Exttable.add ("file","doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2"); //Maximum file size        intMaxSize =1000000;  This. Context =context; Httppostedfile Imgfile= Context. request.files["Imgfile"]; if(Imgfile = =NULL) {ShowError ("Please select a file. "); }        //File TypeString DirName = context. request.querystring["dir"]; if(String.IsNullOrEmpty (dirName)) {DirName="Image"; }        if(!Exttable.containskey (DirName)) {ShowError ("The directory name is incorrect. "); } String fileName=Imgfile.filename; String Fileext=path.getextension (fileName).        ToLower (); if(Imgfile.inputstream = =NULL|| ImgFile.InputStream.Length >maxSize) {ShowError ("The upload file size exceeds the limit. "); }        if(String.IsNullOrEmpty (fileext) | | Array.indexof (((String) exttable[dirname]). Split (','), Fileext.substring (1). ToLower ()) = =-1) {ShowError ("the upload file name extension is not allowed. \ n Allow only"+ ((String) exttable[dirname]) +"format. "); }        varSavedir = context. request["Savedir"]; stringSavedirstr =NULL; if(Savedir = =NULL) {Savedirstr="tmp"; }        Else{savedirstr=savedir.tostring (); }        //whether distributed uploads        BOOLIsDFS =false; varDFS = context. request["DFS"]; if(Dfs! =NULL&& Dfs. ToString () = ="1") {IsDFS=true; } Hashtable Hash=NewHashtable (); if(IsDFS) {varIMAGEURL =Cloud.Utility.ConfigHelper.Images_SITE_URL; varClient =NewRestsharp.restclient (IMAGEURL);//TODO API Base Path            varRequest =NewRestsharp.restrequest ("File/upload", RestSharp.Method.POST); Request. Alwaysmultipartformdata=true; Request. AddHeader ("dir", DirName +"/"+savedirstr); Request. AddHeader ("IMAGEURL", IMAGEURL); Request. AddFile ("file", Cloud.Utility.StreamHelper.ConvertToBytes (Imgfile.inputstream), context.            Server.HTMLEncode (Imgfile.filename)); varPosttask =client.            Executeposttaskasync (Request); if(Posttask. Result.statuscode = =System.Net.HttpStatusCode.OK) {varurl = posttask. Result.Content.Trim (New Char[] {'[',']','"' }); hash["URL"] =URL; }            Else{ShowError ("Distributed upload failure"); }        }        Else        {            //File Save Directory            stringSavepath ="/upload/kindeditor/"+ DirName +"/"+Savedirstr; String Dirpath=context.            Server.MapPath (Savepath); if(!directory.exists (Dirpath))            {directory.createdirectory (Dirpath); } String NewFileName= DateTime.Now.ToString ("_yyyymmddhhmmss_ffff", Datetimeformatinfo.invariantinfo) +Fileext; String FilePath= Dirpath +"/"+NewFileName;            Imgfile.saveas (FilePath); hash["URL"] = Savepath +"/"+NewFileName; } hash["Error"] =0; Context. Response.AddHeader ("Content-type","text/html; Charset=utf-8"); Context.        Response.Write (Jsonmapper.tojson (hash)); Context.    Response.End (); }    Private voidShowError (stringmessage) {Hashtable hash=NewHashtable (); 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 BOOLisreusable {Get        {            return true; }    }}
All Code

The client passes over a file to save the directory parameter: Savedir

The client passes over a parameter that uploads the file to the image server: DFS, if the Dfs=1 representative is uploaded to the picture server, otherwise uploaded to the local

The core code for uploading a file: An open source upload component is used Restsharp

Step three: Webapi image server-side code:

[Route ("File/upload")] [HttpPost] public Async taskPostFormData () {//Check if the request contains Multipart/form-data. if (!Request.Content.IsMimeMultipartContent ()) {throw newHttpresponseexception (Httpstatuscode.unsupportedmediatype); } var dir = Request.Headers.GetValues ("dir").            First (); var imageUrl = Request.Headers.GetValues ("ImageUrl"). First (); String root = System.Web.HttpContext.Current.Server.MapPath (Path.Combine ("~/images/", dir)); if (System.IO.Directory.Exists (root) = = False) {System.IO.Directory.CreateDirectory (root);} var provider = new  Multipartformdatastreamprovider (root); Provider = new Renamingmultipartformdatastreamprovider (root);//Rename the notation await Request.Content.ReadAsMultipartAsync (provider); var urllist = new list<string>(); var url = ""; foreach (multipartfiledata file in provider. FileData) {String path = file. LocalFilename; var start = path. IndexOf ("\\images"); path = path. Substring (start); var mainurl = imageurl;//configurationmanager.appsettings["Mainimageurl"]; url = mainurl + path. Replace ("\ \", "/"); Urllist.add (URL);//return request.createresponse (Httpstatuscode.ok, URL); } return request.createresponse (Httpstatuscode.ok, urllist);}           

Where the file renaming method is:

  <summary>///File Upload and rename///</summary> public class Renamingmultipartformdatastreamprovider:multipartformdatastreamprovider {public string Root {get; set
    
     ; Public Renamingmultipartformdatastreamprovider (String
      root): base(root) {R        Oot = root; } public override string Getlocalfilename (httpcontentheaders headers) {string FilePath = headers.c Ontentdisposition.filename; Multipart requests with the file name seem to always include quotes. if (Filepath.startswith (@ "" "") && Filepath.endswith (@ "" "") FilePath = filepath.substring (1, Filepath.length-2); Return Path.getfilenamewithoutextension (FilePath) + DateTime.Now.ToString ("_yyyymmddhhmmss_ffff", Datetimeformatinfo.invariantinfo) + path.getextension (FilePath). ToLower (); return FilePath;}}          
    

Fourth step: Kindeditor configuration:

The main configuration is the Uploadjson parameter: Savedir represents the saved directory, DFS representative is uploaded to the picture server, if the Dfs=1 representative uploaded to the picture server otherwise uploaded to the local.

Kindeditor Extended paste Image function & Modify image upload path and upload image to image server via Webapi

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.