CKEditor picture Upload for detailed steps (using struts 2)

Source: Internet
Author: User
Tags html form

I use the CKEditor version is 4.7.0

There is a "picture field" in the Editor toolbar of CKEditor, which can add images to a text editor with a patch address, but no image uploads.

There was a lot of birds in the preview, which was very unpleasant. You can open the Ckeditor/plugins/image/dialogs/image.js file and search for "B.config.image_previewtext" to find the birds, (B.config.image_ previewtext| | ') The contents of the single quotation mark are all erased.

The following research pictures upload.

Step 1:

First of all, still image.js this file, search "upload" can find this paragraph

ID: ' Upload ', Hidden:

In fact, the upload function is hidden, change the above to false, and then open the editor, you can find the upload function.

Step 2:

The above is just an upload page. It is also equivalent to an HTML form form, to configure the action requested after clicking on the "Upload to Server" button. Can be configured in Ckeditor/config.js.

Join:

Config.filebrowseruploadurl= "Actions/ckeditorupload";

"Ckeditorupload" is the URL of the request, that is, clicking on this button will post to the Ckeditorupload address for processing, which points to a struts 2 action

<Packageextends= "Struts-default" namespace= "/actions" >    class= " Com.xxx.CkeditorUpload ">    </action>  </ Package

Step 3:

The file upload control is equivalent to <input type= "file" name= "Upload" .../>, whose name is "upload", knowing the name so you can get the file in action.

Private File upload;  // file   Private String Uploadcontenttype;  // file Type   Private String Uploadfilename;   // file  name

All three of these private variables must have a set method. If you don't know, you can learn the Struts 2 file upload first.

Step 4:

If the uploaded image is not in the correct format, you can prompt it at the upload screen.

This hint is not a ckeditor prompt, but it should be responded to in action.

String callback = Servletactioncontext.getrequest (). GetParameter ("Ckeditorfuncnum");    if ([judging condition]) {      out.println ("<script type=\" text/javascript\ ">");        Out.println ("Window.parent.CKEDITOR.tools.callFunction" ("+ Callback +", "", "+") file format is incorrect (must be. jpg/.gif/.bmp/. PNG file) '); " );       Out.println ("</script>");       return NULL ;  }  

Step 5:

This code is the core code of the Struts 2 upload image, upload the image and save it in a directory of the project, and randomly rename it.

Step 6:

Picture upload success, in the directory can also see the picture, this picture upload success. But how do you send pictures to the editor?

Click the OK button to have the following prompt.

Here, to return a JS script in action.

With this piece of code, the image is uploaded successfully, according to the

"img/postimg/" + filename

Relative address, you can use this image, go directly to the "image" page.

Attached: Struts 2 Action Code

 PackageCom.nos.java.action.teacher;ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;ImportJava.io.PrintWriter;ImportJava.text.SimpleDateFormat;Importjava.util.ArrayList;ImportJava.util.Calendar;Importjava.util.Date;Importjava.util.List;ImportJavax.servlet.ServletOutputStream;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importjavax.servlet.http.HttpSession;ImportNet.sf.json.JSONArray;ImportNet.sf.json.JSONObject;Importorg.apache.commons.httpclient.HttpClient;ImportOrg.apache.commons.httpclient.HttpStatus;ImportOrg.apache.commons.httpclient.methods.PostMethod;ImportOrg.apache.commons.httpclient.params.HttpMethodParams;Importorg.apache.commons.lang.StringUtils;ImportOrg.apache.struts2.ServletActionContext;ImportOrg.apache.struts2.convention.annotation.Result;ImportOrg.apache.struts2.convention.annotation.Results;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springside.modules.orm.hibernate.Page;Importcom.nos.base.action.BaseAction;Importcom.nos.base.pojo.MyVisit;ImportCom.nos.base.pojo.UserVo;ImportCom.nos.commons.util.ConstComm;ImportCom.nos.commons.util.InterFaceConstComm;Importcom.nos.commons.util.LoggerUtils;ImportCom.nos.commons.util.PubTool;Importcom.nos.commons.util.ResolveXml;Importcom.nos.java.action.downl.IcpInformatAction;ImportCom.nos.java.pojo.Pro;ImportCom.nos.java.pojo.ProModule;ImportCom.nos.java.pojo.Task;ImportCom.nos.java.service.icp.IProModuleService;ImportCom.nos.java.service.icp.IProService;ImportCom.nos.java.service.icp.ISystemConfigService;ImportCom.nos.java.service.icp.ITaskService;Importcom.nos.java.utils.WriteUtils;ImportCom.nos.java.vo.CompanyVo;Importcom.nos.java.vo.ZtreeVo; @SuppressWarnings ("Serial") @Results ({@Result (name= "List", location = "task_list.jsp"), @Result (name= "Edit", location = "task_edit.jsp")}) Public classTaskmanageractionextendsbaseaction{PrivateFile upload;//filePrivateString Uploadcontenttype;//File TypePrivateString Uploadfilename;//file name//private String Imgearray [] = {". bmp", ". gif", ". Jpe", ". jpeg", ". jpg", ". png"};Private StaticList<string> imglist =NewArraylist<>();Static{Imglist.add (". bmp"); Imglist.add (". gif"); Imglist.add (". Jpe"); Imglist.add (". JPEG"); Imglist.add (". jpg"); Imglist.add (". png");} Public voidUploadimg ()throwsioexception{string postfix= Uploadfilename.substring (Uploadfilename.lastindexof (".")));BooleanFlag =Imglist.contains (postfix); SYSTEM.OUT.PRINTLN (flag); HttpServletResponse Response=Servletactioncontext.getresponse (); HttpServletRequest Request=servletactioncontext.getrequest (); Response.setcontenttype ("Text/html;charset=utf-8");//Servletoutputstream out = Response.getoutputstream ();PrintWriter out =Response.getwriter (); String Callback=servletactioncontext.getrequest (). GetParameter ("Ckeditorfuncnum"); if(!flag) {Out.println ("<script type=\" text/javascript\ ">"); Out.println ("Window.parent.CKEDITOR.tools.callFunction (" +Callback+ ",", "+" ' file format is incorrect (must be. jpg/.gif/.bmp/.png/.jpe/.png file) '); "); //out.println ("window.parent.CKEDITOR.tools.callFunction (" + Callback//+ ",", "+" ' \u6587\u4ef6\u683c\u5f0f\u4e0d\u6b63\u786e\uff08\u5fc5\u987b\u4e3a\u002e\u006a\u0070 \u0067\u002f\u002e\u0067\u0069\u0066\u002f\u002e\u0062\u006d\u0070\u002f\u002e\u0070\u006e\u0067\u6587\u4ef6\ Uff09 ' );Out.println ("</script>");return;}//save pictures by TimeCalendar Calendar =calendar.getinstance ();intYear =Calendar.get (calendar.year);intmonth = Calendar.get (calendar.month) + 1;intDay =Calendar.get (calendar.day_of_month);//Get save timeSimpleDateFormat SDF =NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); String uploaddate= Sdf.format (NewDate ()); String Uploadpath= Servletactioncontext.getservletcontext (). Getrealpath ("/uploadimages") + "\ \" +Year ;//+ "\" + month + "\ \" + Day; //get the real pathif(Month < 10) {Uploadpath= Uploadpath + "\\0" +month;}Else{Uploadpath= Uploadpath + "\ \" +month;}if(Day < 10) {Uploadpath= Uploadpath + "\\0" +Day ;}Else{Uploadpath= Uploadpath + "\ \" +Day ;} File RelPath=NewFile (uploadpath);if(!relpath.exists ()) {Relpath.mkdirs ();} File Savefilepath=NewFile (RelPath,NewDate (). GetTime () +postfix); String ImagePath=Savefilepath.getpath ();intindex = Imagepath.indexof ("UploadImages"); ImagePath=imagepath.substring (index); InputStream is=NewFileInputStream (upload); OutputStream os=NewFileOutputStream (savefilepath);byte[] buffer =New byte[1024]; intLength = 0;  while(length = is.read (buffer)) > 0) {os.write (buffer,0, length);  } is.close (); Os.close (); //String projectName = Request.getcontextpath ();ImagePath = Request.getscheme () + "://" +request.getlocaladdr () + ":" +request.getserverport () +request.getcontextpath ( )+"/"+ImagePath;//ImagePath = (imagePath). ReplaceAll ("\\\\", "\\\\\\\\");ImagePath = (imagePath). ReplaceAll ("\\\\", "/"); Out.println ("<script type=\" text/javascript\ ">"); Out.println ("Window.parent.CKEDITOR.tools.callFunction (" + Callback + ", '" +imagepath + "', ')"); Out.println ("</script>");}}
View Code

CKEditor picture Upload for detailed steps (using struts 2)

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.