Java + Spring + Ueditor for image Upload

Source: Internet
Author: User

The company uses the Alibaba Cloud image server and needs to directly upload the images in the article to the server. However, the uploaded images in this editor are directly uploaded to the Tomcat root directory.

Unable to meet the requirements. I tried to transform the image upload function.

The downloaded editor directly imports the webapp Directory of the project.

Because the Spring Framework is used and basically contains several jar packages required by ueditor, you do not need to import them.

Please note that this jar package of the ueditor-1.1.1.jar, in fact, does not need to be imported, because this package contains only one file Uploader. java

The Uploader. java file already exists in the jsp directory of ueditor, so you can directly copy this file to the workspace and access this file.

Change the directory in the called Place

Set

<% @ Page import = "com. baidu. ueditor. um. Uploader" %>

Change

<% @ Page import = "com. myproject. upload. Uploader" %>

As shown in the following figure:

Then the key is to transform the Uploader. java class.

The original Upload code is as follows:

The code is as follows: Copy code

Public void upload () throws Exception {
Boolean isMultipart = ServletFileUpload. isMultipartContent (this. request );
If (! IsMultipart ){
This. state = this. errorInfo. get ("NOFILE ");
Return;
        }
DiskFileItemFactory dff = new DiskFileItemFactory ();
String savePath = this. getFolder (this. savePath );
Dff. setRepository (new File (savePath ));
Try {
ServletFileUpload sfu = new ServletFileUpload (dff );
Sfu. setSizeMax (this. maxSize * 1024 );
Sfu. setHeaderEncoding ("UTF-8 ");
FileItemIterator fii = sfu. getItemIterator (this. request );
While (fii. hasNext ()){
FileItemStream FCM = fii. next ();
If (! FS. isFormField ()){
This. originalName = FI. getName (). substring (FI. getName (). lastIndexOf (System. getProperty ("file. separator") + 1 );
If (! This. checkFileType (this. originalName )){
This. state = this. errorInfo. get ("TYPE ");
Continue;
                    }
This. fileName = this. getName (this. originalName );
This. type = this. getFileExt (this. fileName );
// Obtain the relative path of the stored file
This. url = savePath + "/" + this. fileName;
BufferedInputStream in = new BufferedInputStream (FCM. openStream ());
File file = new File (this. getPhysicalPath (this. url ));
FileOutputStream out = new FileOutputStream (file );
BufferedOutputStream output = new BufferedOutputStream (out );
// The image file is generated directly in the root directory of the server.
Streams. copy (in, output, true );
This. state = this. errorInfo. get ("SUCCESS ");
This. size = file. length ();
// The UE only processes a single upload and exits after the upload is complete.
Break;
} Else {
String fname = FCM. getFieldName ();
// Only the title is processed. Please process other forms by yourself
If (! Fname. equals ("pictitle ")){
Continue;
                    }
BufferedInputStream in = new BufferedInputStream (FCM. openStream ());
BufferedReader reader = new BufferedReader (new InputStreamReader (in ));
StringBuffer result = new StringBuffer ();
While (reader. ready ()){
Result. append (char) reader. read ());
                    }
This. title = new String (result. toString (). getBytes (), "UTF-8 ");
Reader. close ();
                    
                }
            }
} Catch (SizeLimitExceededException e ){
This. state = this. errorInfo. get ("SIZE ");
} Catch (InvalidContentTypeException e ){
This. state = this. errorInfo. get ("ENTYPE ");
} Catch (FileUploadException e ){
This. state = this. errorInfo. get ("REQUEST ");
} Catch (Exception e ){
This. state = this. errorInfo. get ("UNKNOWN ");
        }
}

After modification:

The code is as follows: Copy code

// The transformed code is commented out by Baidu's original code
Public void upload () throws Exception
    {
Boolean isMultipart = ServletFileUpload. isMultipartContent (this. request );
If (! IsMultipart)
        {
This. state = this. errorInfo. get ("NOFILE ");
Return;
        }
Try
        {
MultipartResolver resolver = new CommonsMultipartResolver (
This. request. getSession (). getServletContext ());
MultipartHttpServletRequest multipartRequest = resolver. resolveMultipart (request );
CommonsMultipartFile orginalFile = (CommonsMultipartFile) multipartRequest. getFile ("upfile ");
            
This. originalName = orginalFile. getOriginalFilename ();
If (! This. checkFileType (this. originalName ))
            {
This. state = this. errorInfo. get ("TYPE ");
Return;
            }
This. type = this. getFileExt (this. originalName );
This. size = orginalFile. getSize ();
            
// This is the tool used to upload files from the company to Alibaba cloud server.
String key = ImgUtils. uploadImage ("xxxx ",
ImageKind. Picture,
OrginalFile. getInputStream (),
This. size );
            
This. fileName = key;
This. url = "http://xxx.aliyuncs.com/" + key;
This. state = this. errorInfo. get ("SUCCESS ");
        }
Catch (Exception e)
        {
This. state = this. errorInfo. get ("UNKNOWN ");
        }
}

These two files of Spring are used.

The code is as follows: Copy code

Import org. springframework. web. multipart. commons. CommonsMultipartFile;
Import org. springframework. web. multipart. commons. CommonsMultipartResolver;

Then, the img src directory needs to be changed when it is displayed on the Editor page.

The code is as follows: Copy code

Callback: function (editor, $ w, url, state ){
If (state = "SUCCESS "){
// Display Image count + 1
Upload. showCount ++;
Var $ img = $ (" "),
Var $ img = $ (" "),
$ Item = $ ("<div class = 'edui-image-item edui-image-upload-item'> <div class = 'edui-image-close'> </div> </div> "). append ($ img );
If ($ (". Edui-image-upload2", $ w). length <1 ){
$ (". Edui-image-content", $ w). append ($ item );
Upload. render (". edui-image-content", 2)
. Config (". Edui-image-upload2 ");
} Else {
$ (". Edui-image-upload2", $ w). before ($ item). show ();
                }
$ Img. on ("load", function (){
Base. scale (this, 120 );
Base. close ($ (this ));
$ (". Edui-image-content", $ w). focus ();
});
} Else {
CurrentDialog. showTip (state );
Window. setTimeout (function (){
CurrentDialog. hideTip ();
},3000 );
            }
Upload. toggleMask ();
        }

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.