Full introduction to Baidu ueditor Web Editor and CMS Integration

Source: Internet
Author: User
Tags httpcontext

Ueditor is a WYSIWYG text Web Editor developed by Baidu Web Front-end R & D department. It has powerful front-end editing functions and integrates practical functions such as online map, code highlight, and progress bar upload, it also supports a large number of Baidu frontend applications. Ruishang enterprise CMS is a website content management system for enterprise users. It supports the frontend website editing mode (free). Before ueditor, its built-in Content Editor is
Tinymce and tinymce are characterized by clean and stable features. However, their functions are slightly thin. ueditor makes up for tinymce's shortcomings to a large extent. for users who want to provide a large number of front-end applications on their websites, ueditor is a good choice. This article is based on the documents recorded by the CMS development team in the integration of the ueditor. It will help other CMS developers understand the detailed integration process of the editor.

Note: As the CMS is based on. therefore, this article is based on ueditor. net Development version ,. net, PHP, and JSP Versions differ in the background processing modules for functions such as image and file upload. Ueditor. NET development edition:
UTF-8 version (v1.2.5.0) | GBK version (v1.2.5.0)

How to integrate ueditor into CMS
  1. Reference ueditor resources and library files on the front-end page, and create an editor instance.
  2. Modify the ueditor configuration file
  3. Background integration of ueditor Image Upload Function
  4. Background integration of ueditor's remote image capturing function
  5. Background integration of management functions in ueditor image sets
  6. Ueditor image editing page Customization
  7. Background integration of ueditor file upload function
  8. Background integration of ueditor's video search function
Reference ueditor resources and library files on the front-end page, and create an editor instance.
  1. Download the latest ueditor version. for integration in CMS, you should download the same development version as your CMs development language. therefore, use ueditor. net version, if your CMs needs to support all languages, it is recommended to use the UTF-8 version.
  2. Decompress the downloaded file to your CMs product directory. The ueditor deployment path in ruishang enterprise CMS is the ueditor directory under the root path. After unzipping the ueditor development edition, there will be a lot of directories, but what you really need is the following:
    Directory: dialogs
    Directory: Lang
    Directory: Themes
    Directory: third-party
    File in the root directory: editor_all_min.js
    File in the root directory: editor_config.js
    Note: The ueditor master database file is editor_all.js, and editor_all_min.js is the compressed version of the code after the blank content is removed. To reduce the size of the reference page, try to use the compressed version of the Code as much as possible.
  3. Add the following reference code (usually in the head) to the page where you want to enable the ueditor ):
     
    Note: assume that the ueditor directory is located in the root path of the website. To facilitate reference in any path, use the absolute path whenever possible.
  4. Create a ueditor editor object on the page: ueditor can create an editor instance on textarea or script. When you use a script object to create an editor instance, you need to set the type attribute of the script to text/plain. The advantage of using the script object is that it can avoid automatic character escape processing by textarea. However, as the ruishang enterprise CMS also integrates the tinymce Editor, we still use textarea to create an editor instance to take into account the two editors. The specific method is as follows (assume that your textarea object's
    The ID attribute is text_content ):
     

    In this way, the teaxtarea object used to edit content on your page will be replaced by the ueditor, And the content generated by the editor during the editor process (HTML code content ), it will be sent to your textarea object at any time for publishing to the background for storage.

Modify the ueditor configuration file

In the above ueditor reference, we have referenced the editor_config.js file, which is the ueditor configuration file. ueditor puts the configuration variables in an independent file, it is convenient for the website's end manager to adjust the editor's performance and behavior outside of the CMS system. Of course, the CMS developer can still call the variables in the configuration file on their pages, use their program logic to change the configuration. During integration with CMS, the following configuration variables are most likely to be used (these variables point to the background processing module customized for ueditor by ruishang enterprise CMS ):

  • , Imageurl: "/admin/resource/ueditorimageupload. aspx"

    This is the background receiving and processing page for image uploading. This page is used to receive published images, save images, and return the information of the images in JSON format for reference by the ueditor.
  • , Fileurl: "/admin/resource/ueditorfileupload. aspx"

    This is the background receiving and processing page for file upload. This page is responsible for receiving published files, saving the files, and returning the corresponding information of the file in JSON format for reference by the ueditor.
  • , Catcherurl: "/admin/resource/ueditorgetremoteimage. aspx"

    After the remote image capture option is enabled, the page will download the remote image you inserted (not the internal image of this site) to this site, so that ueditor can reference it with the address of this site, this function is used in the "Remote Image" and "Image Search" situations in the image insert dialog box. Ueditorgetremoteimage. aspx is customized by the CMS of ruishang enterprise. It is used to download and save remote images to a processing page on this site, this page will eventually return the remote image and capture the image information on this site in JSON format.
    Note: To enable the remote image capturing function, set the catchremoteimageenable parameter in the configuration file to true.
  • , Imagemanagerurl: "/admin/resource/ueditorimagemanager. aspx"

    After uploading a local image to the background of your website in ueditor, you can use this page to manage the image and return to the list of images in the background image storage area for reference by ueditor.
  • , Wordimageurl: "/admin/resource/ueditorimageupload. aspx"

    This page is the same as the previous image uploading background processing page. When you copy and paste the text in the word to the editor, normally, the webpage cannot display the local images in Word. ueditor can upload the local images used in Word to the site background and replace the local images in the word content with the uploaded online images.
  • , Getmovieurl: "/admin/resource/ueditorgetmovie. aspx"

    The backend page specified by this parameter is used to search for potato videos Based on the given keywords and return the search results to the ueditor editor.

In addition to the preceding six parameters, the following variables may be used during ueditor integration with CMS:

  • Toolbars
    This variable is used to customize buttons in the ueditor. Different buttons are separated by commas (,). You can use the "|" character to group different buttons, if you want to artificially distribute buttons to different rows, you can use "[]" to enclose the buttons of the same row. Different rows must be separated by commas.
  • Webappkey
    You can register a developer account in the Developer Center, apply for a webappkey, and put it here. Only webappkey can be inserted into your site. To apply for a webappkey, see
    Http://app.baidu.com/static/cms/getapikey.html.
  • Zindex
    Adjust the Z-index value of the ueditor object based on the layout of the page content in your CMS to prevent the existing objects on your page from blocking the ueditor editor.

The preceding configuration parameters are most likely to be used when the ueditor editor is integrated in CMS. You can also Customize multiple versions of editor_config.js and load them in different scenarios, in order to load different styles of editors in different scenarios, for example, loading the full editor (example) on the webpage content editing page, loading the simplified Editor (example) on the forum or message page ), only a small number of security editing functions are provided.

Background integration of ueditor Image Upload Function

After you deploy ueditor in the preceding steps, most of the functions can be directly used. However, functions such as file upload and other functions also need support from the corresponding background modules to receive, save the uploaded file and return the information of the uploaded file for ueditor to call. The ueditor Image Upload Interface contains four tabs: Remote Image Upload, local upload, online management, and image search. This section describes the background receiving and processing of local image uploads.

The local upload of ueditor images uses a flash component that supports the progress bar. This component browses the Local Computer, selects the image you want to upload, and displays the thumbnail of the image on the upload interface, an image description text box is displayed below the thumbnail. You can enter the image description here and click "Start upload". The image data and description are published to the background, where can I publish it? Is In The ueditor configuration file (editor_config.js)
ImageurlThe address indicated by the variable, which is ueditorimageupload in the/admin/resource path for the cms of the ruishang enterprise. on the ASPX page, the background processing logic in this page will receive the published image data, save the image, and return the corresponding information of the image. The following describes how ueditorimageupload. aspx is implemented:

1. Receive and save released image files

In. Net, a typical method for receiving published files is as follows:

HttpFileCollection myHttpFileCollection=HttpContext.Current.Request.Files;HttpPostedFile myHttpPostedFile=null;if (myHttpFileCollection!=null){if (myHttpFileCollection.Count>0){if (myHttpFileCollection[0].ContentLength>0 && myHttpFileCollection[0].FileName!=""){myHttpPostedFile=myHttpFileCollection[0];}else{myHttpPostedFile=null;}}else{myHttpPostedFile=null;}}else{myHttpPostedFile=null;}

Rui enterprise CMS stores all randomly uploaded files in the folder named by the current date under the/writable/resource/_ random _ path. We will construct the name of this folder:

string myStringDirectory=HttpContext.Current.Server.MapPath(String.Format("/writable/resource/_random_/{0:####}-{1:0#}-{2:0#}",DateTime.Today.Year,DateTime.Today.Month,DateTime.Today.Day));

Then construct the name of the image file to be saved:

string myStringPath=String.Format(@"{0}\{1}",myStringDirectory, Path.GetFileName(myHttpPostedFile.FileName));

Finally, save the released image file.

myHttpPostedFile.SaveAs(myStringPath);

2. Return Image Information

The ueditor Image Upload Component must return the following four information in JSON format in the background:

  • URL: The logical path of the saved image file in step 1 above.
  • Title: The description text of the image filled in on the ueditor Local Image Upload interface. The name of the image description text input text box is "pictitle", so you can use httpcontext. current. request. form ["pictitle"] gets the published image description.
  • Original: The complete physical path after the file is saved in step 1 above.
  • State: In Step 1 above, if the file is successfully saved or not, use the "success" string. If the file fails, use "error ".

Construct the returned JSON data:

string myStringJson=string.Format("{{'url':'{0}','title':'{1}','original':'{2}','state':'{3}'}}",myStringUrl,myStringTitle,myStringOriginal,myStringState);

Finally, if the preceding JSON data is returned, the returned JSON data tells ueditor the necessary information about the uploaded image for ueditor to reference the image in the editor.

Response.ContentType = "text/plain";Response.Write(myStringJson);

Code download

Background integration code of the ueditor Image Upload Function

A randomresourcesave class is used in the Code. The Code in this class is the same as the Code mentioned in "Receive and save published image files, you can replace this class with the code.

Background integration of ueditor's remote image capturing function

On the image editing page of ueditor, in addition to the local image upload function described above, you can also directly provide remote image addresses or search for remote images from the network. The editor can directly insert remote images, you can also download the remote image to the background of this site and then reference it. The latter requires the corresponding background processing program. The ueditorgetremoteimage. ASPX page in the/admin/resource path is used by the CMS to process the download and return of remote images, that is, in the editor_config.js configuration file.
CatcherurlThe address specified by the variable.

Note: To enable the remote image capturing function, set the catchremoteimageenable parameter in the configuration file (editor_config.js) to true.

1. First, obtain the URL of the remote image to be downloaded back to this site.

On the ueditor image editing page, a form control named upfile is used to publish the input or selected remote image to the background, you can use this code to capture the remote image address list:

string myStringRemoteImageUrl = HttpContext.Current.Server.HtmlEncode(HttpContext.Current.Request["upfile"]);

On the remote image search page, ueditor uses the "ue_separate_ue" string to separate the image addresses (this string can be used in the configuration file
SeparaterVariable setting. The default value is "ue_separate_ue"). You can convert the released remote image address to an array using the following code in the background:

string[] myArrayStringRemoteImageUrl=Regex.Split(myStringRemoteImageUrl, "ue_separate_ue", RegexOptions.IgnoreCase);

2. For each remote image file in the array, use the. NET WebClient component to download it to the local site background.

for (int i = 0; i <= myArrayStringRemoteImageUrl.Length-1; i++){myStringCurrentRemoteImageUrl = myArrayStringRemoteImageUrl[i];WebClient myWebClient=new WebClient();myWebClient.DownloadFile(...);}

3. Return the list of image addresses (and other information) downloaded back to the background of the site in JSON format)

myStringReturnImageList=string.Format("{{url:'{0}',tip:'success!',srcUrl:'{1}'}}",this.ConverToString(myArrayListTempName),myStringRemoteImageUrl);Response.ContentType = "text/plain";Response.Write(myStringReturnImageList);

Code download

Ueditor background integration code for remote image capturing

Background integration of management functions in ueditor image sets

The background processing module of the ueditor image editing interface, local upload, remote image, and image search tabs has been completed. The last function is online management, that is, you can obtain the image resource list from the background resource library of this site for reference by ueditor. This function is relatively simple. It is nothing more than reading the list of all images from the specified background image resource path, returns a list separated by a ue_separate_ue string. The background integration address of this function is
ImagemanagerurlVariable specified. In the acute business CMS, this page is the ueditorimagemanager. ASPX page under the/admin/resource path. Let's see how this page is handled:

1. Collect all image addresses in the background image resource path

DirectoryInfo myDirectoryInfoRandomResource=new DirectoryInfo(HttpContext.Current.Server.MapPath(myStringRandomResourceLogicalPath));foreach (DirectoryInfo myDirectoryInfo in myDirectoryInfoRandomResource.GetDirectories()){myStringBuilderReturnImageList.AppendFormat("{0}{1}/{2}ue_separate_ue",myStringRandomResourceLogicalPath,myDirectoryInfo.Name,myFileInfo.Name);}

2. Back to the image list

Response.ContentType = "text/plain";Response.Write(myStringBuilderReturnImageList.ToString());

Code download

Background integration code for the management function in the ueditor image set

Note: The current problem of ueditor image background integration management is that the returned background image set does not have a paging mechanism. If the number of images in the background resource library is large, it will inevitably cause performance problems.

Ueditor image editing page Customization

The CMS provides two modes for the ueditor Editor: full mode and simplified mode. The complete mode provides complete functions for editing page content. The simplified mode provides secure and simplified functions, it is used for forums, messages, and other occasions. For the image editing function of ueditor, the features of the local upload and image management tabs are hidden in simplified mode. To this end, ruishang CMS provides two versions of the editor_config.js configuration file, which is loaded on different occasions. In normal mode, the configuration file is

Editor_config.js. In simplified mode, the configuration file is
Editor_config_simple.js, in simplified mode,ImageurlThe parameter is set to null.

Rui enterprise CMS then customizes the image.html file under the/dialogs/image path. In the four tabs of the tabheads Div, t_remote, t_local, t_imgmanager, t_imgsearch four IDs to facilitate them to be followed by document. getelementbyid reference. In the final script of this file, add the following code to hide the Image Upload and online management tabs:

if (editor.options.imageUrl.length==0){document.getElementById("t_local").style.display="none";document.getElementById("local").style.display="none";document.getElementById("t_imgManager").style.display="none";document.getElementById("imgManager").style.display="none";document.getElementById("t_remote").className="focus";}

Code download

Custom Code on the ueditor image editing page

Background integration of ueditor file upload function

The mechanism of ueditor uploading files is similar to that of image uploading. The background integration module is used to receive published file data and then return the file information in JSON format. The background processing page address for file upload is
FileurlVariable specified. In the acute business CMS, It is the ueditorfileupload. aspx file under the/admin/resource path. Let's take a look at how ueditorfileupload. aspx is done:

1. Receive and save published files

This is the same as the processing method for receiving and storing published images (ueditorimageupload. aspx.

2. Return File Information

The ueditor File Upload Component must return the following four information in JSON format in the background (The filetype parameter is different from the Image Upload component, and the Image Upload Component corresponds to the title parameter ):

  • URL: The logical path of the saved file in step 1 above.
  • Filetype: Format Suffix of the file.
  • Original: The complete physical path after the file is saved in step 1 above.
  • State: In Step 1 above, if the file is successfully saved or not, use the "success" string. If the file fails, use "error ".

Construct the returned JSON data:

string myStringJson=string.Format("{{'url':'{0}','fileType':'{1}','original':'{2}','state':'{3}'}}",myStringUrl,myStringFileType,myStringOriginal,myStringState);

Finally, if the preceding JSON data is returned, the returned JSON data tells ueditor the necessary information about the uploaded image for ueditor to reference the image in the editor.

Response.ContentType = "text/plain";Response.Write(myStringJson);

3. Solve the session loss problem

Unlike image uploading, in a browser other than the IE kernel, the file uploading component will lose the session information on the current page, and the login information stored in the cookie cannot be passed to the background processing page, the logon fails. The solution of CMS is to use JavaScript in/dialogs/attachment/attachment.html to read authenticationticket stored in the cookie and pass it to the background processing page through post_params, the background processing page restores the passed authenticationticket information
Cookie storage is equivalent to passing the logon cookie in twists and turns.

In attachment.html, find

 

Add the following code after it:

 

This code references the basic JavaScript Library (commonjavascript. JS), which contains the getcookie () function. You can also write a getcookie () function and put it in the attachment.html file for reference. The code of the getcookie function is as follows:

function GetCookie(name){var cname = name + "=";               var dc = document.cookie;             if (dc.length > 0){              begin = dc.indexOf(cname);               if (begin != -1)        {           begin += cname.length;       end = dc.indexOf(";", begin);            if (end == -1) end = dc.length;            return unescape(dc.substring(begin, end));}}return null;}

In attachment.html, find

post_params:{"PHPSESSID":"<?php echo session_id(); ?>"},

Modify it

post_params:{"AuthenticationTicket":GetCookie("AuthenticationTicket")},

Finally, capture the published authenticationticket parameter in ueditorfileupload. aspx and restore it to a cookie:

HttpRequest myHttpRequest=HttpContext.Current.Request;string myStringAuthenticationTicket=myHttpRequest.Form["AuthenticationTicket"];HttpCookie myHttpCookie=new HttpCookie("AuthenticationTicket",myStringAuthenticationTicket);myHttpCookie.Expires=DateTime.Now.AddMinutes(480);myHttpRequest.Cookies.Set(myHttpCookie);

The above code must be placed before the load event of the aspx file.

Code download

Customization of the attachment.html File
Background integration code of the ueditor file upload function

Background integration of ueditor's video search function

The video search function uses the Tudou API of the video website to search for Tudou and return the search result to ueditor for reference. The background integration address of this function is
GetmovieurlThe page referred to by the variable is the ueditorgetmovie. ASPX page under the/admin/resource path in the cms of the ruishang enterprise. Let's see how this page is handled:

1. Intercepted search keywords and search types published on the ueditor video editing page

string myStringSearchKey = HttpContext.Current.Server.HtmlEncode(HttpContext.Current.Request["searchKey"]);string myStringVideoType = HttpContext.Current.Server.HtmlEncode(HttpContext.Current.Request["videoType"]);

2. Potato API address

Uri myUriTudouSearch = new Uri(string.Format("http://api.tudou.com/v3/gw?method=item.search&appKey=myKey&format=json&kw={0}&pageNo=1&pageSize=20&channelId={1}&inDays=7&media=v&sort=s",myStringSearchKey,myStringVideoType));

3. Use the WebClient component to access the potato API

WebClient myWebClient = new WebClient();Byte[] myArrayBytePageData = myWebClient.DownloadData(myUriTudouSearch.ToString()); myString=Encoding.UTF8.GetString(myArrayBytePageData);

4. Return results

Response.ContentType = "text/plain";Response.Write(myString);

Code download

Background integration code of the ueditor video search function

Note: The video search function currently returns very limited results because many keyword searches do not return any results.
Conclusion

If you do not consider background integration of images, file uploads, and other functions, the integration of ueditor with any CMS can be as simple as several lines of code, it is nothing more than adding a reference to the ueditor resources and library files on the page, and then rendering the editor to the textarea or JavaScript Object on the page through the render method of the ueditor instance object. If you want to implement image and file upload functions, You need to design the corresponding processing module in your CMs background to process the image or file data published on the ueditor interface, return the file information to the Editor interface for reference. The CMS of ruishang enterprise implements the ueditor
It is hoped that the above integration process will be helpful to all CMS developers for background integration of most features.

Source: Official CMS website of ruishang enterprise, which is compiled by the CMS development team of ruishang enterprise.

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.