Use xheditor in jsp

Source: Internet
Author: User

 

 

Xheditor-1.1.7 editor plugin http://download.csdn.net/detail/huahuagongzi9999/7130273

 

 

First, create a web project: test-xheditor. The directory structure is as follows:

 

2, by, import the corresponding xheditor file, lib package [commons-fileupload-1.2.1.jar, commons-io-1.3.2.jar,

Commons-lang-2.4.jar, servlet-api.jar], index. jsp.

 

Iii. System constant class: SystemConstants. class,

 

/*****/Package com. xheditor. contants;/*** @ author hu. shiguo * @ time 11:57:14 * @ description System constant * @ version */public class SystemConstants {public static String WEB_ROOT = null ;}

Iv. Initialization Configuration class: SystemListener. class ,

 

 

/*****/Package com. xheditor. listener; import javax. servlet. servletContextEvent; import javax. servlet. servletContextListener; import com. xheditor. contants. systemConstants;/*** @ author hu. shiguo * @ time 11:50:36 * @ description system load listener, you can load some configurations to the memory when the web container is started * @ version */public class SystemListener implements ServletContextListener {/* (non-Javadoc) * @ see javax. servlet. servletContextListener # contextDestroyed (javax. servlet. servletContextEvent) */@ Overridepublic void contextDestroyed (ServletContextEvent event) {}/ * (non-Javadoc) * @ see javax. servlet. servletContextListener # contextInitialized (javax. servlet. servletContextEvent) * // @ Overridepublic void contextInitialized (ServletContextEvent event) {String webRoot = event. getServletContext (). getRealPath (/); System. out. println (webRoot); SystemConstants. WEB_ROOT = webRoot ;}}

 

 

5. File Upload class: UploadFileServlet. class,

 

Package com. sportevents. servlet; import java. io. file; import java. io. IOException; import java. io. printWriter; import java. io. serializable; import java. text. simpleDateFormat; import java. util. date; import java. util. hashMap; import java. util. iterator; import java. util. list; import java. util. map; import java. util. UUID; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servle T. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import org. apache. commons. fileupload. diskFileUpload; import org. apache. commons. fileupload. fileItem; import org. apache. commons. lang. stringUtils; import com. sportevents. contants. systemConstants; @ SuppressWarnings ({serial, deprecation}) public class UploadFileServlet extends HttpServlet {private static String baseFileDir = File. sepa Rator + uploadFile + File. separator; // upload the file storage directory private static String baseURLDir =/uploadFile/; // upload the file directory URLprivate static String fileExt = jpg, jpeg, bmp, gif, and png; private static Long maxSize = 0l; // 0: do not create a directory 1: Save the directory by day 2: Save the directory by month 3: it is recommended to save directories by extension by saving private static String dirType = 1;/*** File Upload initialization work */public void init () throws ServletException {/* obtain the equivalent path of the file upload and storage */if (! StringUtils. isBlank (this. getInitParameter (baseDir) {baseFileDir = this. getInitParameter (baseDir);} String realBaseDir = this. getServletConfig (). getServletContext (). getRealPath (baseFileDir); File baseFile = new File (realBaseDir); if (! BaseFile. exists () {baseFile. mkdir ();}/* get the file type parameter */fileExt = this. getInitParameter (fileExt); if (StringUtils. isBlank (fileExt) fileExt = jpg, jpeg, gif, bmp, png;/* get the file size parameter */String maxSize_str = this. getInitParameter (maxSize); if (StringUtils. isNotBlank (maxSize_str) maxSize = new Long (maxSize_str);/* get the file directory type parameter */dirType = this. getInitParameter (dirType); if (StringUtils. isBlank (dirType) dirType = 1; if (, 0, 1, 2, 3 ,. indexOf (, + dirType +,) <0) dirType = 1;}/*** Upload File data processing process */@ SuppressWarnings ({unchecked}) public void doPost (HttpServletRequest request, httpServletResponse response) throws ServletException, IOException {response. setContentType (text/html; charset = UTF-8); response. setHeader (Cache-Control, no-cache); String err =; String newFileName =; DiskFileUpload upload = new DiskFileUpload (); try {List
 
  
Items = upload. parseRequest (request); Map
  
   
Fields = new HashMap
   
    
(); Iterator
    
     
Iter = items. iterator (); while (iter. hasNext () {FileItem item = (FileItem) iter. next (); if (item. isFormField () fields. put (item. getFieldName (), item. getString (); elsefields. put (item. getFieldName (), item);}/* obtain the form Upload File */FileItem uploadFile = (FileItem) fields. get (filedata);/* get the file upload path name */String fileNameLong = uploadFile. getName (); System. out. println (fileNameLong: + fileNameLong);/* get the file extension * // * the effect of adding 1 to the index is only xxx.. Jpg */String extensionName = fileNameLong. substring (fileNameLong. lastIndexOf (.) + 1); System. out. println (extensionName: + extensionName);/* check the file type */if (, + fileExt. toLowerCase () + ,). indexOf (, + extensionName. toLowerCase () +,) <0) {printInfo (response, this type of file cannot be uploaded,); return;}/* Whether the file is empty */if (uploadFile. getSize () = 0) {printInfo (response, the uploaded file cannot be blank,); return;}/* check the file size */if (maxSize> 0 & uploadFile. GetSize ()> maxSize) {printInfo (response, the size of the uploaded file exceeds the limit,); return;} // 0: do not create a directory, 1: Save the directory by day, 2: save to the directory by month. 3. Save the directory by extension. we recommend that you use daily storage. string fileFolder =; if (dirType. repeated signorecase (1) fileFolder = new SimpleDateFormat (yyyyMMdd ). format (new Date (); if (dirType. repeated signorecase (2) fileFolder = new SimpleDateFormat (yyyyMM ). format (new Date (); if (dirType. repeated signorecase (3) fileFolder = extensionName. toLowerCase (); // Project Record String projectPath = SystemConstants. WEB_ROOT; File files = new File (projectPath); // upload the File storage directory String uploadFilePath = files. getParent () + File. separator + uploadFile + File. separator + fileFolder + File. separator; // String uploadFilePath = files. getPath () + File. separator + uploadFile;/* relative path of file storage * // String saveDirPath = baseFileDir + fileFolder +/; // System. out. println (saveDirPath: + saveDirPath);/* the file is stored in the container Absolute path * // String saveFilePath = this. getServletConfig (). getServletContext (). getRealPath () + baseFileDir + fileFolder +/; System. out. println (saveFilePath: + uploadFilePath);/* build the File directory and directory File */File fileDir = new File (uploadFilePath); if (! FileDir. exists () {fileDir. mkdirs ();}/* rename the file */String filename = UUID. randomUUID (). toString (); File savefile = new File (uploadFilePath + filename +. + extensionName);/* store the uploaded file */System. out. println (upload = null); uploadFile. write (savefile); // String projectBasePath = request. getScheme () +: // + request. getServerName () +: + request. getServerPort () + request. getContextPath (); String projectBasePath = request. getScheme () +: // + request. getServerName () +: + request. getServerPort (); newFileName = projectBasePath + baseURLDir + fileFolder +/+ filename +. + extensionName; System. out. println (newFileName: + newFileName);} catch (Exception ex) {System. out. println (ex. getMessage (); newFileName =; err = Error: + ex. getMessage ();} printInfo (response, err, newFileName );} /*** output json data using an I/O stream * @ param response * @ param err * @ param newFileName * @ throws IOException */public void printInfo (HttpServletResponse response, string err, String newFileName) throws IOException {PrintWriter out = response. getWriter (); // String filename = newFileName. substring (newFileName. lastIndexOf (/) + 1); out. println ({err: + err +, msg: + newFileName +}); out. flush (); out. close ();}}
    
   
  
 


 

Vi. web. xml: Mainly configures servlet for listening and uploading files

 

   
  
   com.xheditor.listener.SystemListener
    
 
      
  
   UploadFileServlet
       
  
   com.xheditor.servlet.UploadFileServlet
    
   
      
  
   UploadFileServlet
       
  
   /servlet/UploadFileServlet
    
 

VII. jsp page:

 

 

 

<% @ Page language = java import = java. util. * pageEncoding = UTF-8 %> <% @ taglib uri = http://java.sun.com/jsp/jstl/core prefix = c %>
 
  
<% String path = request. getContextPath (); String basePath = request. getScheme () +: // + request. getServerName () +: + request. getServerPort () + path +/; %>
  
  />
  
  
  
  
  
  
  <Script type = text/javascript src =$ {ctx}/xheditor-1.1.7/jquery/jquery-1.4.2.min.js> </script> <script type = text/javascript src =$ {ctx}/xheditor-1.1.7/ xheditor-1.1.7-zh-cn.min.js> </script> <script type = text/javascript src =$ {ctx}/js/yz. js> </script> <script type = text/javascript> $ (document ). ready (function () {// initialize the xhEditor plug-in $ ('# xh_editor '). xheditor ({tools: 'full', skin: 'default', upMultiple: true, upImgUrl: servlet/UploadFileServlet, upImgExt: jpg, jpeg, gif, bmp, png, onUpload: insertUpload, html5Upload: false}); // function of the Image Upload callback in the xbhEditor: insertUpload (msg) {var _ msg = msg. toString (); // var _ picture_name = _ msg. substring (_ msg. lastIndexOf (/) + 1); // var _ picture_path = Substring (_ msg); // var _ str =
  
  + _ Picture_name +
  
; // Alert (xh_editor = before = + $ (# xh_editor ). val (); $ (# xh_editor ). append (_ msg); // $ (+ _ msg ). appendTo ($ (# clubDesc); // alert (xh_editor = end = + $ (# xh_editor ). val ();} // The string content returned by the processing server to the callback function. The format is JSON. function Substring (s) {return s. substring (s. substring (0, s. lastIndexOf (/)). lastIndexOf (/), s. length);} // save $ (# save ). bind (click, function () {// var xh_editor =$ (# xh_editor ). val (). replace (/s/g,); // alert (last = + xh_editor); document. getElementById (froms ). submit () ;}); </script>


 

8. Final effect:

 

 

 

 

 

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.