JS control kindeditor realize picture automatic upload function _javascript skill

Source: Internet
Author: User
Tags httpcontext

Kindeditor is a powerful open source online HTML editor that supports WYSIWYG editing results. It is written in JavaScript and can be seamlessly integrated with a number of different locales, such as. NET, PHP, ASP, Java, and so on. The official website can be viewed here: http://kindeditor.net/index.php

Kindeditor itself offers a number of very useful plug-ins that developers can extend and modify as needed because of the open source of the code.

Consider a scenario when editing Web content using Kindeditor: Editors tend to copy content from other pages or Word documents into the Kindeditor editor rather than start writing from a blank sheet of paper. If the copied content contains pictures, you need to first download the picture from the source address to the local, and then upload it to the server on this site, otherwise the picture will still point to the page you copied or the document, which will cause the picture may not open correctly on the page. Editors often have to deal with a lot of documents, which is certainly cumbersome. Can you let kindeditor automatically recognize what you pasted into it and upload the picture to the server automatically? The following code implements this functionality.

For information on how to use Kindeditor on a page, you can view the documentation for the official website, which is not detailed here.

The basic idea of implementing this function is to add code to the KeyUp event in the Kindeditor editor to check whether the editor's contents contain pictures, find pictures that need to be uploaded to the server automatically, and call the image upload program via Ajax, uploading the picture to the server. The SRC address of the corresponding picture is modified to the local relative address in the Ajax callback function.

This feature does not support copying pictures from Word and uploading them to the server.


The above diagram is the ultimate implementation effect. The program automatically recognizes the contents of the editor, and if a picture needs to be uploaded, a message is displayed at the top of the editor. Users click on the "Upload" link, the program will call the image upload program via AJAX request, and in the callback function of the corresponding picture of the SRC address modified to the local relative address.

Specific implementation steps and related code:

1. Kindeditor Editor Modification

Locate the Kindeditor.js file and add the custom code to the KeyUp () event. Different versions of Kindeditor may provide a larger code difference that needs to be found with the help of an official document. This article is based on Kindeditor version 4.1.10.


2. auto.js File Code

function df () {var haspiccontainer = document.getElementById ("Has_pic");
  if (Haspiccontainer = = null) {Haspiccontainer = document.createelement ("div");
  Haspiccontainer.id = "Has_pic"; haspiccontainer.innerhtml = "<input type= ' text ' id= ' piclist ' value= '" style= ' display:none; ' /><div id= ' upload ' ><b> you have pictures to upload to server </b>  <a href= ' javascript:uploadpic (); ' >
  Upload </a></div><div id= ' confirm ' ></div> ';
 $ (". Ke-toolbar"). After (Haspiccontainer);

 var img = $ (". Ke-edit-iframe"). Contents (). FIND ("img");
 var piccount = 0;
 var sstr = "";
  $ (IMG). Each (function (i) {var, = $ (this);
   if (that.attr ("src"). IndexOf ("http://") >= 0 | | that.attr ("src"). IndexOf ("https://") >= 0) {piccount++;
   if (i = = $ (img). length-1) Sstr + + + that.attr ("src");
  else Sstr + = that.attr ("src") + "|";

 }
 });
 $ ("#piclist"). Val (SSTR); document.getElementById ("Has_pic"). Style.display = (Piccount > 0)?
"Block": "None";function Closeupload () {$ ("#has_pic"). Hide ();
$ ("#upload"). Show ();
 function Uploadpic () {var piclist = encodeURI ($ ("#piclist"). Val ());

 if (Piclist.length = = 0) return false; $.ajax ({url: "asp.net/uploadpic.ashx", Data: "pic=" + piclist, type: "Get", Beforesend:function () {$ ("#uplo
   Ad "). Hide ();
  $ ("#confirm"). Text ("in upload ...");
    }, Success:function (msg) {if (msg!== "") {var str = new Array ();
    str = msg.split (' | ');

    var img = $ (". Ke-edit-iframe"). Contents (). FIND ("img");
     $ (IMG). Each (function (i) {var, = $ (this); if (that.attr ("src"). IndexOf ("http://") >= 0 | | that.attr ("src"). IndexOf ("https://") >= 0) {that.attr ("src",
      "/uploads/image/" + str[i]);
     That.attr ("Data-ke-src", "/uploads/image/" + str[i]);

    }
    }); $ ("#confirm"). HTML (img.length + "picture has been uploaded successfully!")   <a href= ' javascript:closeupload (); '
   > Close </a> "); else $ ("#confirm"). Text ("Upload failed!")
  ");
}
 });

 }

The $ (". Ke-edit-iframe"). Contents (). FIND ("img") is used to look up all the pictures in the editor's content. By default, the contents of the editor are stored in an IFRAME element, which has the properties of the class= "Ke-edit-iframe". The program determines whether the value of each picture src attribute contains "http://" or "https://" to determine if the picture is a remote picture or a local picture. If the picture is a remote picture, call Uploadpic.ashx through the Ajax method of jquery to upload the picture to the server. Also modify the SRC address of the corresponding picture in the callback function.

3. uploadpic.ashx File Code

public class Uploadpic:ihttphandler {public void ProcessRequest (HttpContext context) {context.
  Response.ContentType = "Text/plain"; String pic = context.

  request.querystring["pic"]; string[] arr = pic.
  Split (' | ');
  String sstr = "";
  Uploadimg st = new Uploadimg (); for (int i = 0; i < arr. Length; i++) {if (Arr[i]. IndexOf ("http://") >= 0 | | Arr[i]. IndexOf ("https://") >= 0) {String std = St. Saveurlpics (Arr[i], ". /..
    /uploads/image/"); if (Std. Length > 0) {if (i = = arr.
     LENGTH-1) Sstr + + std;
    else Sstr + = std + "|"; }} context.
 Response.Write (SSTR);
  public bool IsReusable {get {return false;
  }} public class Uploadimg {public string saveurlpics (string imgurlary, String path) {string strhtml = "";

  String dirpath = HttpContext.Current.Server.MapPath (path); try {if (!
   Directory.Exists (Dirpath)) {directory.createdirectory (Dirpath); } String ymd = Datetime.noW.tostring ("YyyyMMdd", datetimeformatinfo.invariantinfo);
   Dirpath + = Ymd + "/"; if (!
   Directory.Exists (Dirpath)) {directory.createdirectory (Dirpath); String newfilename = DateTime.Now.ToString ("Yyyymmddhhmmss_ffff", Datetimeformatinfo.invariantinfo) +

   Imgurlary.substring (Imgurlary.lastindexof ("."));
   WebClient WC = new WebClient (); Wc.
   DownloadFile (imgurlary, Dirpath + newfilename);
  strHTML = Ymd + "/" + NewFileName; The catch (Exception ex) {//return ex.
  message;
 return strhtml;

 }
}

Remote pictures are downloaded to the server's relative path "/uploads/image/" by the WebClient method, and the folders and corresponding file names are automatically generated by date. The returned result contains a "|" The local relative address of all pictures separated, in the Uploadpic () function of Step 2 of the Auto.js file, the callback method success gets the value and resolves it, assigning the address to the SRC attribute of the corresponding picture.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.