Java Implementation of image uploading in xheditor and image uploading in xheditor

Source: Internet
Author: User

Java Implementation of image uploading in xheditor and image uploading in xheditor

In a recent project, because of the framework, many text editors are not compatible. Finally, xheditor is found. This Rich Text Editor is indeed good and has basic functions, only the java interface for uploading images needs to be written by yourself. Therefore, the two methods are tested and eventually succeeded. Share with you.

Xheditor provides the upload interface. Therefore, we only need to call our own Action to return a json data in the json format specified by it.

 

1. servlet implementation method, servlet implementation method needs to introduce the commons-fileupload-1.3.1.jar package. It is mainly used to parse requests sent from the front-end.

1. The front-end page writing method should introduce xheditor. I will write it here. In this example, the upImgUrl is used to write your backend Servlet.

<textarea class="editor" name="articleContent" rows="35" cols="100" style="z-index:99;"         upImgUrl="UploadFileServlet" upImgExt="jpg,jpeg,gif,png" >    ${article.articlecontent }</textarea>

2. Write servlet in the background. I also omitted the configuration file. Here is just a Servlet. Please note that here we will introduce the commons-fileupload-1.3.1.jar package to parse the request.

Package com. zk. web. action; import java. io. file; import java. io. IOException; import java. util. iterator; import java. util. list; import javax. servlet. servletConfig; import javax. servlet. servletContext; import javax. servlet. servletException; import javax. servlet. servletOutputStream; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import org. apache. commons. fileupload. fileItem; import org. apache. commons. fileupload. disk. diskFileItemFactory; import org. apache. commons. fileupload. servlet. servletFileUpload; public class UploadFileServlet extends HttpServlet {private static final long serialVersionUID = 1L; private ServletContext SC; public void init (ServletConfig config) {SC = config. getServletContext ();} protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this. doPost (request, response);} protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {ServletOutputStream out = response. getOutputStream (); request. setCharacterEncoding ("UTF-8"); response. setHeader ("Content-Type", "text/html"); String returnPath = ""; DiskFileItemFactory factory = new DiskFileItemFactory (); ServletFileUpload upload = new ServletFileUpload (factory ); try {List items = upload. parseRequest (request); Iterator iter = items. iterator (); while (iter. hasNext () {FileItem item = (FileItem) iter. next (); System. out. println ("Size of the uploaded file:" + item. getSize (); System. out. println ("File Upload type:" + item. getContentType (); System. out. println ("Name of the uploaded file:" + item. getName (); returnPath = "images/" + item. getName (); // obtain the Project address File forder = new File (SC. getRealPath ("/") + "images /");
// Determine whether the folder exists if (! Forder. exists () {forder. mkdir ();} File file = new File (SC. getRealPath ("/") + "images/" + item. getName (); item. write (file); System. out. println ("File Uploaded successfully! ") ;}} Catch (Exception e) {e. printStackTrace (); System. out. println ("failed to upload file");} // the key is to return the address of the uploaded image stored on the server. The path is adjusted according to the path of your project. Out. print ("{'err':'', 'msg ':' "+ returnPath. replace ("\", "/") + "'}");}}

II. Implementation Method When spring mvc is used. UploadImage is an Action,

1. The front-end page writing method should introduce xheditor. I will write it here. UpImgUrl is mainly used to write your background Action.

<textarea class="editor" name="articleContent" rows="35" cols="100" style="z-index:99;"         upImgUrl="uploadImage.do" upImgExt="jpg,jpeg,gif,png" >    ${article.articlecontent }</textarea>

2. Write the background Action. Here the sping mvc framework is used. spring has never been tested. If you need it, try it.

/*** Upload an image in the text editor * @ param request * @ param response * @ return * @ throws Exception */public void uploadImage (HttpServletRequest request, HttpServletResponse response) throws Exception {ServletOutputStream out = response. getOutputStream (); request. setCharacterEncoding ("UTF-8"); response. setHeader ("Content-Type", "text/html"); CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver (request. getSession (). getServletContext (); // sets the encoding commonsMultipartResolver. setDefaultEncoding ("UTF-8"); if (commonsMultipartResolver. isMultipart (request) {MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile image = multipartRequest. getFile ("filedata"); String url = "images" + File. separator + Tool. dateToString (new Date (), "yyyyMMdd") + File. separator;
// Obtain the address String filePath = "D:/" + url; Random r = new Random (); if (image! = Null &&! Image. isEmpty () {InputStream xtins = image. getInputStream (); String hj = new String (image. getOriginalFilename (). getBytes ("ISO-8859-1"), "UTF-8"); hj = hj. split ("\\. ") [1];
// Generate the file name String fileName = Tool. dateToString (new Date (), "yyyyMMddHHmmss") + r. nextInt (1000) + ". "+ hj; saveInputStreamToFile (filePath, fileName, xtins );
// Here is the out that is returned to xheditor. print ("{'err':'', 'msg ':' "+ (url + fileName ). replace ("\", "/") + "'}");}}} /*** save the file flow to the specified path * @ param filePath * @ param fileName * @ param inputStream * @ throws Exception */public void saveInputStreamToFile (String filePath, String fileName, InputStream inputStream) throws Exception {OutputStream OS = null; try {File forder = new File (filePath); if (! Forder. exists () {forder. mkdir ();} File file = new File (filePath + fileName); OS = new FileOutputStream (file); int bytesRead = 0; byte [] buffer = new byte [8192]; while (bytesRead = inputStream. read (buffer, 0, 8192 ))! =-1) {OS. write (buffer, 0, bytesRead);} OS. close (); inputStream. close ();} catch (Exception ex) {ex. printStackTrace (); throw ex;} finally {if (inputStream! = Null) {inputStream. close ();} if (OS! = Null) {OS. close ();}}}

How to upload images in FCKeditor in java

Create a folder named mysite in tomcat> webapps. Copy the/editor, fckconfig. js, FCKeditor. js, fckstyles. xml, and fcktemplates. xml files in fckeditor to the mysite folder, because other files are meaningless to us. Then put FCKeditor. java 2.3 in the web directory under the WEB-INF directory copy to mysite (which has commons-fileupload.jar, FCKeditor-2.3.jar, web. xml and other files), put the FCKeditor under the src directory. tld files copy to mysite/WEB-INF. in this way, JSP is supported.

Modify some of the files below:
Open the fckconfig. js file and modify FCKConfig. DefaultLanguage = ''zh-cn '';
Replace the values of FCKConfig. LinkBrowserURL with the following:
FCKConfig. LinkBrowserURL = FCKConfig. BasePath + "filemanager/browser/default/browser.html? Connector = connectors/jsp/connector ";

FCKConfig. ImageBrowserURL = FCKConfig. BasePath + "filemanager/browser/default/browser.html? Type = Image & Connector = connectors/jsp/connector ";

FCKConfig. FlashBrowserURL = FCKConfig. BasePath + "filemanager/browser/default/browser.html? Type = Flash & Connector = connectors/jsp/connector ";

FCKConfig. LinkUploadURL = FCKConfig. BasePath + ''filemanager/upload/simpleuploader? Type = File '';

FCKConfig. FlashUploadURL = FCKConfig. BasePath + ''filemanager/upload/simpleuploader? Type = Flash '';

FCKConfig. ImageUploadURL = FCKConfig. BasePath + ''filemanager/upload/simpleuploader? Type = image '';

Open the web. xml file under the WEB-INF:
Define the Configuration Attribute enabled in SimpleUploader as true (enable the file upload function)
Add Tag definition:
<Taglib>
<Taglib-uri>/mysite </taglib-uri>
<Tagl ...... remaining full text>

How does java upload images to the server and preview images?

Preview, cannot simply use , and then assign the address to src, there will be browser incompatibility issues
Use a css Filter, as shown below
Document. getElementById ("previewImg "). style. filter = "progid: DXImageTransform. microsoft. alphaImageLoader (sizingMethod = 'Scale', src = '"+ o. value + "')";
As for how to upload, struts2 is very convenient

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.