Ueditor picture upload how to integrate with real projects

Source: Internet
Author: User
Tags call back stub

1. first, We define a servlet named getconfigservlet, the real project should be a controller, the same class is loaded back-end configuration file class

Package Com.ay.servlet;import Java.io.ioexception;import Javax.servlet.servletexception;import Javax.servlet.annotation.webservlet;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import com.baidu.ueditor.actionenter;/** * This class is mostly get config file * @author Ay * Servlet implementation class Getconfigservlet */@WebServle T ("/getconfigservlet") public class Getconfigservlet extends HttpServlet {private static final Long Serialversionuid =    1L;    /** * @see httpservlet#httpservlet () */public getconfigservlet () {super (); }/** * @see httpservlet#doget (httpservletrequest request, httpservletresponse response) */protected void D Oget (httpservletrequest request, httpservletresponse Response) throws servletexception, IOException {//here is the contro        ller.jsp code copy down request.setcharacterencoding ("utf-8");        Response.setheader ("content-type", "text/html"); String RoolpAth = request.getsession (). getservletcontext (). getrealpath ("/");        Remember to put Config.json under/test/web-inf/String configstr = new Actionenter (request, roolpath). exec ();        System.out.println (roolpath);    Response.getwriter (). Write (configstr); }/** * @see httpservlet#dopost (httpservletrequest request, httpservletresponse response) */protected void DoPost (httpservletrequest request, httpservletresponse Response) throws servletexception, IOException {}}

Here is a picture of my Code distribution:

2. Modify the Ueditor.config to change the ServerURL path to the Back-end interface path we wrote ourselves, that is, Getconfigservlet class

//原来    // 服务器统一请求接口路径, serverUrl: URL + "jsp/controller.jsp"//改为, serverUrl: URL + "GetConfigServlet"

3. The above can be loaded out Rich text box, here is introduced a JS class Loadconfig.js:

    (function () {UE.        Editor.prototype.loadServerConfig = function () {var me = this; SetTimeout (function () {try{me.options.imageUrl && me.setopt (' serverurl ', Me.options.ima Geurl.replace (/^ (. *[\/]). + ([\.].                +) $/, ' $1controller$2 ');                var configurl = Me.getactionurl (' config '), isjsonp = Utils.iscrossdomainurl (configurl);                /* make an ajax request */me._serverconfigloaded = false; Configurl && UE.ajax.request (configurl,{' method ': ' GET ', ' DataType ': Isjson P?  ' Jsonp ': ', ' onsuccess ': function (r) {try {var config = isjsonp?                            R:eval ("(" +r.responsetext+ ")");                            Utils.extend (me.options, config);                            Me.fireevent (' serverconfigloaded ');                        me._serverconfigloaded = true; } catch(e) {showerrormsg (me.getlang (' loadconfigformaterror ')); }}, ' onerror ': function () {showerrormsg (me.getlang (' loadconfi                    Ghttperror '));            }                });            } catch (e) {showerrormsg (me.getlang (' loadconfigerror '));        }        });            function showerrormsg (msg) {console && console.error (msg);        Me.fireevent (' showmessage ', {//' title ': msg,//' type ': ' ERROR '//});    }    }; Ue.        Editor.prototype.isServerConfigLoaded = function () {var me = this; return me._serverconfigloaded | |    False    }; Ue.        Editor.prototype.afterConfigReady = function (handler) {if (!handler | |!utils.isfunction (handler)) return;        var me = this;            var readyhandler = function () {handler.apply (me, arguments); Me.removelistener ('serverconfigloaded ', readyhandler);        };        If (me.isserverconfigloaded ()) {handler.call (me, ' serverconfigloaded ');        } else {me.addlistener (' serverconfigloaded ', readyhandler); }    };}) ();

4. But have not found a problem, call the service side of the unified interface has been loaded configuration file to occupy, then upload the file interface is not, How to do it, how to do it???

In fact, Ueditor official website in the fifth chapter has been said, see the fifth Chapter:

How to customize the request address
This document explains how to modify the request Address.

Application Scenarios
Ueditor 1.4.2+ recommends using a unique request address with the Get parameter action to specify a different request Type. But many users want to use their own written upload address, the following provides a workaround: because all ueditor requests through the editor Object's Getactionurl method to obtain the request address, can be directly implemented by the method of replication, such as the Following:

UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;UE.Editor.prototype.getActionUrl = function(action) {    if (action == ‘uploadimage‘ || action == ‘uploadscrawl‘ || action == ‘uploadimage‘) {        return ‘http://a.b.com/upload.php‘;    } else if (action == ‘uploadvideo‘) {        return ‘http://a.b.com/video.php‘;    } else {        return this._bkGetActionUrl.call(this, action);    }}

This is an official document, as long as you overwrite the Getactionurl in the Prototype.

5. we'll Start by creating a class: fileuploadservlet.java, the code for handling file uploads

Package Com.ay.servlet;import Java.io.ioexception;import Javax.servlet.servletexception;import Javax.servlet.annotation.webservlet;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import javax.servlet.http.httpservletresponse;/** * servlet implementation Class Fileuploadservlet */@WebServlet ("/fileuploadservlet") public class Fileuploadservlet extends HttpServlet {privat    E static final Long serialversionuid = 1L;        /** * @see httpservlet#httpservlet () */public fileuploadservlet () {super (); TODO auto-generated Constructor stub}/** * @see httpservlet#doget (httpservletrequest request, httpservletre Sponse response) */protected void doget (httpservletrequest request, httpservletresponse Response) throws Servletex ception, IOException {//TODO auto-generated Method stub}/** * @see httpservlet#dopost (httpservletrequ EST request, httpservletresponse response) */protected void DoPost (HttpServletRequest request, httpservletresponse Response) throws servletexception, IOException {}} 

second, Modify the CONFIG.JSO configuration file, Change the value of Imageactionname to upload the file path, as Follows:

 /* 上传图片配置项 */"imageActionName": "fileUploadServlet", /* 执行上传图片的        action名称 */

finally, we add the following code on the Simpleupload.html:

<!    DOCTYPE html>

Class for picture uploads:

Package Com.ay.servlet;import Java.io.ioexception;import Javax.servlet.servletexception;import Javax.servlet.annotation.webservlet;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import javax.servlet.http.httpservletresponse;/** * servlet implementation Class Fileuploadservlet */@WebServlet ("/fileuploadservlet") public class Fileuploadservlet extends HttpServlet {privat    E static final Long serialversionuid = 1L;        /** * @see httpservlet#httpservlet () */public fileuploadservlet () {super (); TODO auto-generated Constructor stub}/** * @see httpservlet#doget (httpservletrequest request, httpservletre Sponse response) */protected void doget (httpservletrequest request, httpservletresponse Response) throws Servletex ception, IOException {//TODO auto-generated Method stub}/** * @see httpservlet#dopost (httpservletrequ EST request, httpservletresponse response) */protected void DoPost (HttpServletRequest request, httpservletresponse Response) throws servletexception, IOException {//this is the real code in our Project.        File upload is definitely a POST request System.out.println ("--------picture upload successful---------------");        System.out.println ("------------------------------");    System.out.println ("--------image Upload successful-----------"); }}

This is basically the end of the story, but did you find that there was a problem

In general, the upload interface for our project and the JSON data returned to the front end are fixed, but the JSON format required by Ueditor is not the same as the JSON data returned in our Project.

In general, the upload interface for our project and the JSON data returned to the front end are fixed, but the JSON format required by Ueditor is not the same as the JSON data returned in our Project.

In general, the upload interface for our project and the JSON data returned to the front end are fixed, but the JSON format required by Ueditor is not the same as the JSON data returned in our Project.

See Below:

first, Let's look at the JSON data returned after the successful upload of the ueditor image

{"state": "SUCCESS","original": "80px - \u526f\u672c (2).jpg","size": "13252","title": "1465731377326075274.jpg","type": ".jpg","url": "/ueditor/jsp/upload/image/20160612/1465731377326075274.jpg"}

In other words, if we call our own image upload interface, The returned JSON data will be transformed into the JSON data required by ueditor, where can we change it?

In the callback of Simpleupload.js

Function callback () {try{var link, json, loader, BODY = (iframe. contentdocument | | iframe.contentWindow.document). body, result = Body.innertext | | body.textcontent | |                    ‘‘; The result here is the JSON data returned by our real project//very simply write a method that turns the old JSON into ueditor required json Oldjson = (new functio                    N ("return" + result));                    This method was written by me to convert var json = Changedatatojson (json);                    link = me.options.imageUrlPrefix + json.url;                        if (json.state = = ' SUCCESS ' && json.url) {loader = me.document.getElementById (loadingid);                        Loader.setattribute (' src ', link);                        Loader.setattribute (' _src ', link); Loader.setattribute (' title ', Json.title | | |                        ‘‘); Loader.setattribute (' alt ', Json.original | |                        ‘‘); Loader. removeattribute (' ID ');                    Domutils.removeclasses (loader, ' Loadingclass ');                    } else {showerrorloader && showerrorloader (json.state); }}catch (er) {showerrorloader && showerrorloader (me.getlang (' simpleupload.loader                Ror '));                } Form.reset ();            domutils.un (iframe, ' Load ', callback); }/** Write your own method, you can implement **/function Changedatatojson (json) {var object = {"original":                ', ' size ': ', ' state ': ', ' title ': ', ' type ': ', ' url ': '};                var _json = json; 。。。。。 The logic of your own real project//.....            The logical return object of your own real project; }

In fact, this is basically the end of the writing, but there is a problem

is, in general, we upload pictures, will be uploaded to the Server's disk, such as: C or D disk, not very will put it in the project deployment directory, because once the project is redeployed, the picture will disappear

This raises a problem, first look at the following can be successfully uploaded and displayed pictures, Notice that the picture is put into the project/ueditor/jsp/upload ... directory, so no Problem.

however, our real project is placed in the Non-tomcat directory, such as the C,d disk, this time, is this:

If this is the case or, Google Chrome will report:

The workaround is To:

This method is a controller layer of our real project, providing a way to get a picture stream

/** * 根据ID获取图片流 * * @param id * @param request * @param response * @throws IOException */@RequestMapping(value = "/{id}/image", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)public void image(@PathVariable("id") String id,        HttpServletRequest request, HttpServletResponse response)        throws IOException {    SysAttachment sysAttachment = sysAttachmentService.findById(id);    AssertUtils.checkResourceFound(sysAttachment);    response.setContentType("image/x-png");    response.setCharacterEncoding("UTF-8");    File file = new File(sysAttachment.getPath());    BufferedImage image = ImageIO.read(file);    ImageIO.write(image, sysAttachment.getType(), response.getOutputStream());}

That is, continue to get the picture by calling the backend interface

At this point, the IMG Note becomes, The following "xxx/xxx/image" is the real Project controller mapping path

well, It's really over ...

finally, a picture is used to express the above Logic:

Ueditor picture upload how to integrate with real projects

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.