ueditor+ Seven cow, achieve direct image upload

Source: Internet
Author: User

Recently done projects involving the use of rich text editor, I chose Baidu's ueditor. At the same time, our images are placed on seven cow cloud storage. Regarding the integration between the two, I write down some personal experiences to share with you.

Picture uploading scheme

For now, there are two ways to upload images of web-based cloud storage, such as seven cattle, into the following categories:

1. Upload the image to the server and forward the data to seven kn.

Through the server to accept users upload content, while the content can be effectively audited, rejected the content of substandard, and then upload the content from the server to seven cattle.

This method can effectively control and record user-submitted content, but also increase the operating pressure of the server.

2. Upload the image directly to seven kn and then notify the server.

Eliminate the constraints of server bandwidth bottleneck, using the advantages of CDN greatly improve the upload speed, while using seven of callback and magic variables and other characteristics, to obtain the basic information of uploading pictures.

Obviously, the second solution can greatly optimize the experience during the upload process, while also reducing the operating pressure of the own server.

This article will then describe how to make a direct upload of a picture by modifying the ueditor.

Service-Side implementation

The service side needs to implement two interfaces, namely the Ueditor configuration issued and seven cattle upload tokens issued.

1. Ueditor Configuration Issued

There is nothing complicated in this part, that is to put the Ueditor configuration file on the server side, the method can be described in the backend deployment instructions and the source code in the ASP.

In addition, the configuration also modifies the following content

    /* Upload Picture Configuration item *    /"IMAGEURL": "http://up.qiniu.com/",    "Imageactionname": "Uploadimage",/* Perform the action name of the upload picture */    "Imagefieldname": "File",/* submitted picture form name *    /"imagemaxsize": 2048000,/* Upload size limit, Unit B *    /"imageallowfiles": [ c7/> ". jpg", ". JPEG"],/* Upload picture format display *    /"imagecompressenable": true,/* whether to compress the picture, the default is true *    /"Imagecompressborder": 1600,/* picture compression longest edge limit *    /"imageinsertalign": "None",/* insert the picture floating way *    /"Imageurlprefix": "/http 7xkcdc.com2.z0.glb.qiniucdn.com/",/* Image access Path prefix *    /" Imagepathformat ":" Upload/image/{yyyy}{mm}{dd}/{time}{rand : 6} ",/* Upload save path, can customize save path and file name format */

imageUrl: Fill in the address of the seven cattle upload service directly here

imageurlprefix: prefix of picture path

2. Seven KN upload token (token) issued

Based on the seven-cow form upload model, each time the client uploads the image, it needs to get the upload token (token) used in the upload transaction. Because the token generation security requirements are relatively high, it is designed to be implemented on the server side.

This can be used to speed up development with the C#SDK provided by seven kn.

    var key = Makekey ();  Generate key    var ret = new    {        URL = "$ (key)",        key = "$ (key)",        w = "$ (imageinfo.width)",        h = "$ (imageinf O.height) ", state        =" SUCCESS "    };    var policy = new Putpolicy (Bucket)    {        Savekey = key,        returnbody = Jsonconvert.serializeobject (ret)    };    Return policy. Token ();
There are two points to note here.

1. According to the Ueditor two-time development backend request specification, Ueditor needs to return the state and URL fields after successful upload, that is, seven KN is required to return the above fields.

2. For the 1th requirement, we use custom content response (Returnbody) and magic variables to customize the field information we need to return to the client.

Modify Ueditor Code The following is the basic idea of the upload process

1. Editor initialization and obtaining configuration information from the server

2. Get seven KN tokens from the server before uploading, and attach to the upload request

3. Upload images to seven KN server

First, let's analyze what scenarios in Ueditor are involved in image uploads?

Summary down is: Single image upload, multi-image upload (Image Manager), directly drag the picture into the editor upload.

Let's start with a multi-image upload (Image manager).

1. Image Manager upload

The Image Manager code is mainly focused on dialogs/image/image.js

You can see that there is a definition when the editor initializes, where ActionURL uploads the server address.

where editor.getopt (' imageactionname ') means reading the imageactionname from the configuration, viewing the server configuration and knowing that the value is configured as "Uploadimage"

Obviously, this side is done with the centralized management of the configuration, so we found Ueditor/ueditor.all.js (possibly the lower version of Ueditor in _src/core/ Editor.js) and make changes, will involve the upload action scene request address is changed to ImageUrl, that is, seven cattle service address.

        Getactionurl:function (action) {            var actionname = this.getopt (action) | | action,                IMAGEURL = this.getopt (' ImageUrl '),                ServerURL = this.getopt (' ServerURL ');/* Plus Red code *            /if (action = = "Uploadimage") {                return IMAGEURL;            }            if (!serverurl && imageUrl) {                ServerURL = Imageurl.replace (/^ (. *[\/]). + ([\.]. +) $/, ' $1controller$2 ');            }            if (ServerURL) {                ServerURL = ServerURL + (serverurl.indexof ('? ') = =-1? '? ': ' & ') + ' action= ' + (ActionName | | ");                Return Utils.formaturl (ServerURL);            } else {                return ';            }        }

Next we go back to Dialogs/image/image.js and find the event before the upload begins, where we attach the seven tokens from the server, noting that Ajax is called synchronously. This is where jquery gets tokens through Ajax and is placed in the data["token".

2. Drag the picture into the editor to upload

This part of the code is mainly focused on ueditor/ueditor.all.js (Legacy path _src/plugins/autoupload.js)

Here we see the configuration of the upload path, since we have already unified the path obtained by the code, so this section can skip

Find the part that performs the upload, add the red code with the code that was similarly attached to get token

/* Create AJAX and submit */
var xhr = new XMLHttpRequest (),
FD = new FormData (),
params = Utils.serializeparam (Me.querycommandvalue (' Serverparam ')) | | ‘‘,
url = utils.formaturl (ActionURL + (Actionurl.indexof ('? ') = =-1? '? ': ' & ') + params);

Fd.append (fieldName, file, File.name | | (' blob. ' + file.type.substr (' image/'. length));
Fd.append (' type ', ' Ajax ');

$.ajax ({

DataType: "JSON",

Async:false,

URL: ".. /upload/token ",

Success:function (res) {

Fd.append ("token", Res.token);

}

});

Xhr.open ("Post", url, True);
Xhr.setrequestheader ("X-requested-with", "XMLHttpRequest");

3. Single image upload

Seemingly the simplest feature, in fact, left a cross-domain pit. I looked through the single-image upload code, found that it is implemented by an IFRAME, and then use the form to upload.

See the official documentation for an explanation of cross-domain issues with form upload requests, and I don't have time to delve into it at the moment.

ueditor+ Seven cow, achieve direct image upload

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.