Use Kindeditor to upload images and kindeditor to upload images

Source: Internet
Author: User

Use Kindeditor to upload images and kindeditor to upload images

Rich text needs to be added to the project created for the customer. I have read from the Internet that many people recommend the kindeditor editor. It also feels good after using it, some problems occur when uploading images. Record them here for later viewing.

First download kindeditor compressed package on the official website, (I used here is the kindedito-4.1.7), decompress open, jsp, plugins, skins, kindeditor. js, kindedditor-min.js into your own project (I put under the new folder kindeditor webroot), other can not put.

The downloaded package contains a demo. For details, see upload_json.jsp.

<% @ Page language = "java" contentType = "text/html; charset = UTF-8" pageEncoding = "UTF-8" %> <% @ page import = "java. util. *, java. io. * "%> <% @ page import =" java. text. simpleDateFormat "%> <% @ page import =" org. apache. commons. fileupload. * "%> <% @ page import =" org. apache. commons. fileupload. disk. * "%> <% @ page import =" org. apache. commons. fileupload. servlet. * "%> <% @ page import =" org. json. simple. * "%> <% // file storage directory path String SavePath = pageContext. getServletContext (). getRealPath ("/") + "attached/"; // URLString saveUrl = request. getContextPath () + "/attached/"; // defines the file extension HashMap <String, String> extMap = new HashMap <String, String> (); extMap. put ("image", "gif, jpg, jpeg, png, bmp"); extMap. put ("flash", "swf, flv"); extMap. put ("media", "swf, flv, mp3, wav, wma, wmv, mid, avi, mpg, asf, rm, rmvb"); extMap. put ("file", "doc, docx, xls, xl Sx, ppt, htm, html, txt, zip, rar, gz, bz2 "); // maximum file size long maxSize = 1000000; response. setContentType ("text/html; charset = UTF-8"); if (! ServletFileUpload. isMultipartContent (request) {out. println (getError ("select a file. "); Return;} // check the directory File uploadDir = new File (savePath); if (! UploadDir. isDirectory () {out. println (getError ("the upload directory does not exist. "); Return;} // check the directory write permission if (! UploadDir. canWrite () {out. println (getError ("the upload directory has no write permission. "); Return;} String dirName = request. getParameter (" dir "); if (dirName = null) {dirName =" image ";} if (! ExtMap. containsKey (dirName) {out. println (getError ("directory name is incorrect. "); Return;} // create a folder named savePath + = dirName +"/"; saveUrl + = dirName +"/"; File saveDirFile = new File (savePath ); if (! SaveDirFile. exists () {saveDirFile. mkdirs ();} SimpleDateFormat sdf = new SimpleDateFormat ("yyyyMMdd"); String ymd = sdf. format (new Date (); savePath + = ymd + "/"; saveUrl + = ymd + "/"; File dirFile = new File (savePath); if (! DirFile. exists () {dirFile. mkdirs ();} FileItemFactory factory = new DiskFileItemFactory (); ServletFileUpload upload = new ServletFileUpload (factory); upload. setHeaderEncoding ("UTF-8"); List items = upload. parseRequest (request); Iterator itr = items. iterator (); while (itr. hasNext () {FileItem item = (FileItem) itr. next (); String fileName = item. getName (); long fileSize = item. getSize (); if (! Item. isFormField () {// check the file size if (item. getSize ()> maxSize) {out. println (getError ("the size of the uploaded file exceeds the limit. "); Return;} // check the extension String fileExt = fileName. substring (fileName. lastIndexOf (". ") + 1). toLowerCase (); if (! Arrays. <String> asList (extMap. get (dirName ). split (",")). contains (fileExt) {out. println (getError ("the File Upload extension is not allowed. \ N only supports the "+ extMap. get (dirName) +" format. "); Return;} SimpleDateFormat df = new SimpleDateFormat (" yyyyMMddHHmmss "); String newFileName = df. format (new Date () + "_" + new Random (). nextInt (1000) + ". "+ fileExt; try {File uploadedFile = new File (savePath, newFileName); item. write (uploadedFile);} catch (Exception e) {out. println (getError ("failed to upload the file. "); Return;} JSONObject obj = new JSONObject (); obj. put ("error", 0); obj. put ("url", saveUrl + newFileName); out. println (obj. toJSONString () ;}%> <%! Private String getError (String message) {JSONObject obj = new JSONObject (); obj. put ("error", 1); obj. put ("message", message); return obj. toJSONString () ;}%>

Add the following code on the page where we use kindeditor, where item is a tab. Here we add options as needed.

<script charset="utf-8" src="../js/kindeditor-4.1.7/kindeditor.js"></script><script charset="utf-8" src="../js/kindeditor-4.1.7/lang/zh_CN.js"></script>KindEditor.ready(function(K) {                window.editor = K.create('#editor_id', {                    items : ['source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste',        'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',        'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',        'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',        'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',        'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image',        'flash', 'media', 'insertfile', 'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',        'anchor', 'link', 'unlink', '|', 'about'],afterChange : function() {this.sync();}                }                );        });

  Then modify Plugins --> image. js

Replace

UploadJson = K. undef (self. uploadJson, self. basePath + 'php/upload_json.php '),

Change

UploadJson = K. undef (self. uploadJson, self. basePath + 'jsp/upload_json.jsp '),

Finally, do not forget to create a new directory named attached under our tomcat directory to store our images. In upload_json.jsp, the default folder for storing images is attached. I am also exploring this method, hoping to communicate with you.

 

Related Article

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.