Summernote Rich Text Editor

Source: Internet
Author: User
Tags bind getmessage save file split trim cloudflare tomcat server toastr

Recently, to make a publishing article page, select the Summernote in the Rich text editor
Compared to the ckeditor,summernote to be a lot simpler, simple to just introduce CSS and JS on it.
Configuration Application Reference for CKEditor I wrote the article before
CKEditor Series Articles

First look at the effect of Summernote

Summernote See without any configuration, the introduction of CSS and JS to complete the text mix

Official example

<! DOCTYPE html> 

But the picture is Base64 encoded, if you want to save the database will be a bit large.
So upload the image to the server and return to the path. The first step

Rewrite image upload callback function

Callbacks: {
    onimageupload:function (files) {
        //Picture upload method
        uploadimages (files);
    }
,
Step Two

Insertimage the uploaded image into the Summernote editor.

Mysummernote.summernote (' Insertimage ', CTX + Result.data[i].url, result.data[i].filename);

The specific code

$ (document). Ready (function () {//summernote var mysummernote = $ ('. Summernote '); Summernote Editor Configuration mysummernote.summernote ({lang: ' ZH-CN ',//Language height:300,//Height Minhei
            ght:300,//min. Height placeholder: ' Please enter the contents of the article ',//hint callbacks: {//callback function//The callback function used when uploading a picture
            Onimageupload:function (Files) {//Specific upload image method UploadImages (files); }},///Summernote Custom Configuration toolbar: [[' Operate ', [' Undo ', ' Redo '], [' Magic ', [' St  Yle '], [' Style ', [' bold ', ' italic ', ' underline ', ' clear ']], [' Para ', [' height ', ' fontsize ', ' ul ', ' ol ',
          ' Paragraph '], [' Font ', [' Strikethrough ', ' superscript ', ' subscript ']], [' Color ', [' color ']],
    [' Insert ', [' Picture ', ' video ', ' Link ', ' table ', ' HR ']], [' Layout ', [' fullscreen ', ' CodeView ']],]}) Summernote specific upload image method function uploadimages (Files) {//Here are files because I have set up multiple images that I can upload, so I need to add them sequentially to formdata//progress bar $ ("#loadingText"). HTML ("Uploading pictures ...
        0% ");
        $ ("#loadingToast"). Show ();
        Upload a picture of the form var formData = new FormData ();
        For (f in Files) {formdata.append ("file", Files[f]);
        }//XMLHttpRequest object var xhr = new XMLHttpRequest ();
        Xhr.open ("Post", CTX + '/uploadimage ', true);
                Xhr.onreadystatechange = function () {if (xhr.readystate = = Xmlhttprequest.done && Xhr.status = = 200) {
                Console.info ("Upload complete");
                var result = $.parsejson (Xhr.responsetext);
                Console.info (result);
                    if (Result.code = = "") {console.info ("file path");
                    Console.info (result); For (i in Result.data) {//Call Insertimage to insert the uploaded picture into the Summernote editor Mysummernote.summ Ernote (' Insertimage ', CTX + result.data[i].url, result.data[i].filename);
                } $ ("#loadingToast"). Hide ();
                    }else{$ ("#loadingToast"). Hide ();
                Toastr.error ("Picture upload failed:" + result.data);
        }
            }
        };
        Xhr.upload.addEventListener ("Progress", progressfunction, false);
    Xhr.send (FormData); }//progress bar function Progressfunction (evt) {if (evt.lengthcomputable) {var completepercent = Ma
            Th.round (evt.loaded/evt.total * 100) + "%";
            Console.info (completepercent);
            $ ("#loadingText"). HTML ("Uploading pictures ..." + completepercent);
            if (completepercent== "100%") {$ ("#loadingText"). HTML ("Image upload succeeded, processing");
    }
        }
    };
    var CTX = $ ("#ctx"). Val (). Trim ();
        $ ("#publishArticleBtn"). Click (function () {var name=$ ("#articleName"). Val (). Trim ();
            if (name.length==0) {Nodefocus ($ ("#articleName")); Return;
            } if (Mysummernote.summernote (' IsEmpty ')) {toastr.error (' Please enter the content of the article ');
        Return
        } var content = Mysummernote.summernote (' code ');
    Alert ("article content <br>" +content); })
});

Springmvc processing picture uploads

Package com.jcms.controller.admin;
Import java.io.IOException;
Import java.util.ArrayList;

Import java.util.List;

Import Javax.servlet.http.HttpServletRequest;
Import Org.springframework.stereotype.Controller;
Import org.springframework.web.bind.annotation.RequestMapping;
Import Org.springframework.web.bind.annotation.RequestMethod;
Import Org.springframework.web.bind.annotation.RequestParam;
Import Org.springframework.web.bind.annotation.ResponseBody;

Import Org.springframework.web.multipart.MultipartFile;
Import Com.jcms.context.BaseReturn;
Import Com.jcms.context.Param;

Import Com.jcms.util.ImageUtil; /** * Image upload, there may be the front end also to upload pictures, so no/admin management * * @author Cheng Gaowei * @date March 27, 2017 afternoon 5:41:11 */@Controller public class Fileup Loadcontroller {/** * summernote image upload processing, can handle uploading multiple pictures at the same time * * @param files * @param request * @return * @throws IOException */@RequestMapping (value = "/uploadimage", method = Requestmethod.post, Produc ES = "Application/json;charset=utf8 ") @ResponseBody public String Uploadmultiplefilehandler (@RequestParam (" file ") multipartfile[] F Iles, HttpServletRequest request) throws IOException {list<image> images = new Arraylist<&gt
        ;();
            for (Multipartfile file:files) {String URL = imageutil.saveimage (request, file, param.image_upload);
            Image image = new image ();
            Image.seturl (URL);
            Image.setfilename (File.getoriginalfilename ());
        Images.add (image);
    } return Basereturn.response (images);
        } public class Image {//image after upload path private String URL;

        Name of the uploaded image private String fileName;
        Public String GetUrl () {return URL;
        } public void SetUrl (String url) {this.url = URL;
        } public String GetFileName () {return fileName;
   } public void Setfilename (String fileName) {         This.filename = FileName; } @Override Public String toString () {return "Image [url=" + URL + ", filename=" + fileName
        + "]";
 }

    }

}

Imageutil

Package com.jcms.util;
Import Java.awt.image.BufferedImage;
Import Java.io.File;

Import java.io.IOException;
Import Javax.imageio.ImageIO;
Import Javax.imageio.stream.ImageOutputStream;

Import Javax.servlet.http.HttpServletRequest;
Import Org.apache.commons.io.FileUtils;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;

Import Org.springframework.web.multipart.MultipartFile;

Import Net.coobird.thumbnailator.Thumbnails;

    public class Imageutil {private final static Logger Logger = Loggerfactory.getlogger (Imageutil.class); /** * When uploading a picture, save the file to local * * @param request * @param file * @param uploadpath * Shape as this Kind of/assets/upload/image/* @return/assets/upload/image/abc.jpg * @throws ioexception * */public static S Tring SaveImage (httpservletrequest request, Multipartfile file, String uploadpath) {//If a Tomcat server is used, the file is uploaded to \\%t String fileName = file in the omcat_home%\\webapps\\yourwebproject\\uploadpath\\ folder.Getoriginalfilename ();
        String fileext[] = filename.split ("\ \");
        String ext = fileext[fileext.length-1];
        Logger.debug ("-----file suffix: {}-----", ext);
            if (filename.equals (EXT)) {//Unknown file type Logger.error ("-----Unknown file type, file has no suffix-----");
        return null;
        }//String ext = File.getcontenttype (). Split ("\\/") [1];
        String NewFileName = uuidgenerator.getuuid () + "." + ext;
        String Realpath = Request.getservletcontext (). Getrealpath (Uploadpath);
        String filepathandname = null;
        if (Realpath.endswith (File.separator)) {filepathandname = Realpath + newfilename;
        } else {filepathandname = Realpath + File.separator + newfilename;
        } logger.info ("-----uploaded file: {}-----", filepathandname); try {//Save file to local Fileutils.copyinputstreamtofile (File.getinputstream (), new file (Realpath, NEWFI
        Lename)); } catch (IOException E1){logger.error ("-----file saved to local exception: {}-----", e1.getmessage ());
        }//Then compress processing thumbimage (filepathandname);
    return Uploadpath + newfilename; }/** * Delete file * * @param request * @param filePath * @return */public static Boole An DeleteFile (HttpServletRequest request, String filePath) {string realpath = Request.getsession (). Getservletcon
        Text (). Getrealpath (FilePath);
        Logger.info ("-----The path of the file to be deleted: {}-----", Realpath);
        File File = new file (Realpath);
            try {fileutils.forcedelete (file);
        return true;
            } catch (IOException e) {logger.info ("-----Delete picture exception: {}-----", e.getmessage ());
        return false; }}/** * Image compression greater than 2M of 0.5 compression ratio less than 1M of 0.8 compression ratio * * @param imagerealpath * picture on the absolute path of the disk, such as C : \\file.jpg */public static void Thumbimage (String imagerealpath) {File File = new file (imAgerealpath);
        if (File.length () >= * 1024x768 * 2) {thumbimage (Imagerealpath, 0.5); } else if (File.length () < 1024x768 * 1024x768 * 2 && file.length () >= * 1024x768 * 1) {thumbimage (IMA
        Gerealpath, 0.8);
        } else {thumbimage (Imagerealpath, 1); }} public static void Thumbimage (String imagerealpath, double size) {Logger.info ("for picture compression, path: {}, scale: {}",
        Imagerealpath,size);
        if (size-1==0) {return;
        try {thumbnails.of (Imagerealpath). scale (size). ToFile (Imagerealpath);
            } catch (IOException e) {logger.error ("-----Read picture exception: {}-----", e.getmessage ());
            Logger.info ("-----Try CMYK conversion-----");
            File Cmykjpegfile = new file (Imagerealpath);
                try {bufferedimage image = Imageio.read (cmykjpegfile);
           Imageoutputstream output = Imageio.createimageoutputstream (Cmykjpegfile);     if (!
                Imageio.write (image, "jpg", Output)) {Logger.info ("-----CMYK Conversion exception: {}-----");
                } thumbnails.of (image). Scale (0.4f). ToFile (Imagerealpath);
            Logger.info ("-----CMYK conversion success-----");
            } catch (IOException E1) {logger.info ("-----CMYK Conversion exception: {}-----", e1.getmessage ());
 }
        }
    }

}

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.