CKEditor 3 Open File Upload function (servlet implementation)

Source: Internet
Author: User
Tags current time file upload xmlns root directory
It programmer development Essentials-all kinds of resources download list, history of the most IT resources, personal collection summary.


This paper is based on the introduction of http://sarin.iteye.com/blog/599056 to further research.

In the CKEditor upload configuration to open, very simple, the script section changed to the following settings:

<script type= "Text/javascript" >  
	 window.onload = function ()   
     {  
       ckeditor.replace (' Editor1 ', {
          filebrowseruploadurl:ckeditor.basepath+ ' uploader? Type=file ',  
          filebrowserimageuploadurl:ckeditor.basepath+ ' uploader? Type=image ',  
          filebrowserflashuploadurl:ckeditor.basepath+ ' uploader? Type=flash '  
            });
      
    </script>  
Here we can set the parameters ourselves, add a type in order to distinguish the file type, because all use the same servlet processing. Things are not so simple, ckeditor is a complex component after all, we configure, see what it restores to us, in Firefox using Firebug view, see these:

See, after the type it is for us to hook up a few parameters, which we need is the Ckeditorfuncnum and file domain Name value upload,ckeditorfuncnum This parameter is used to callback the page, that is, after the upload is successful, the page automatically switch to The Images tab. The upload parameter is the parameter name used by the servlet to get the uploaded file. The remaining parameters are as needed.
The names of these parameters are obtained from the view source and cannot be taken for granted. With these things behind the good, is the file upload it. It's very simple. Here we use the fileupload and IO in the Apache Commons component.
First look at Web. XML, let's do some setup.

<?xml version= "1.0" encoding= "UTF-8"?> <web-app version= "2.5" xmlns= "Http://java.sun.com/xml/ns/javaee" Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http ://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "> <servlet> <servlet-name>simpleuploader</serv Let-name> <servlet-class>edu.editor.CKEditorUploadServlet</servlet-class> <init-para M> <param-name>baseDir</param-name> <param-value>/userfiles/</param-va lue> </init-param> <init-param> <param-name>debug</param-name&gt  
            ; <param-value>false</param-value> </init-param> <init-param> < Param-name>enabled</param-name> <param-value>true</param-value> </init-par Am> &LT;init-param> <param-name>AllowedExtensionsFile</param-name> <param-value&gt ;</param-value> </init-param> <init-param> <param-name>deniedext Ensionsfile</param-name> <param-value> html|htm|php|php2|php3|php4|php5|phtml|  
        PWML|INC|ASP|ASPX|ASCX|JSP|CFM|CFC|PL|BAT|EXE|COM|DLL|VBS|JS|REG|CGI|HTACCESS|ASIS|FTL </param-value> </init-param> <init-param> <param-name>allowedextensionsimage</para  
        M-name> <param-value>jpg|gif|jpeg|png|bmp</param-value> </init-param> <init-param> <param-name>DeniedExtensionsImage</param-name> <param-val ue></param-value> </init-param> <init-param> <param-name>allo wedextensionsflash</param-name> <param-value>swf|fla</param-value> </init-param> <ini T-param> <param-name>DeniedExtensionsFlash</param-name> <param-value>< /param-value> </init-param> <load-on-startup>0</load-on-startup> &LT;/SERVL et> <servlet-mapping> <servlet-name>SimpleUploader</servlet-name> <ur l-pattern>/ckeditor/uploader</url-pattern> </servlet-mapping> <welcome-file-list> <w
 Elcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
This is primarily the initialization parameters of the servlet, which specifies the file upload extension rule, which is the type that is allowed to upload and the type of block upload. Divided into file,image and flash three kinds, this upload parameter settings are corresponding. Debug is to set the servlet to debug, which is off by default. Enabled is to set whether the servlet is valid, or False if the upload is forbidden. Another basedir is to set the location where the CKEditor upload file is stored.
Here is the implementation class, longer, but with detailed comments:

Package edu.editor;  
Import java.io.*;  
Import Java.text.SimpleDateFormat;  
Import java.util.*;  
Import javax.servlet.ServletException;  
Import javax.servlet.http.*;  
Import Org.apache.commons.fileupload.FileItem;  
Import Org.apache.commons.fileupload.FileItemFactory;  
Import Org.apache.commons.fileupload.disk.DiskFileItemFactory;  
Import Org.apache.commons.fileupload.servlet.ServletFileUpload;  public class Ckeditoruploadservlet extends HttpServlet {private static String basedir;//ckeditor root directory private static Boolean debug = false;//whether the debug mode private static Boolean enabled = false;//is turned on ckeditor upload private St  atic Hashtable allowedextensions;//allowed upload file extension private static Hashtable deniedextensions;//blocked upload file extension private Static SimpleDateFormat dirformatter;//directory naming format: yyyymm private static SimpleDateFormat fileformatter;//file naming format: Yyyym  MDDHHMMSSSSS/** * servlet Initialization method */public void init () throws Servletexception {
        Read Debug Mode debug = (new Boolean (Getinitparameter ("Debug)") from Web. Booleanvalue (); if (Debug) System.out. println ("\ r \ n----Simpleuploaderservlet initialization started  
        ----");  
        Format directory and file naming method Dirformatter = new SimpleDateFormat ("Yyyymm");  
        Fileformatter = new SimpleDateFormat ("Yyyymmddhhmmsssss");  
        Get the root directory name from web. BaseDir = Getinitparameter ("BaseDir");  
        Gets whether the file upload from Web. XML is enabled = (New Boolean (Getinitparameter ("Enabled")). Booleanvalue ();  
        if (BaseDir = = null) BaseDir = "/userfiles/";  
        String Realbasedir = Getservletcontext (). Getrealpath (BaseDir);  
        File Basefile = new file (Realbasedir);  
        if (!basefile.exists ()) {basefile.mkdirs ();  
        }//Instantiate allowed extensions and blocked extensions allowedextensions = new Hashtable (3);  
        Deniedextensions = new Hashtable (3); //Read configuration information from web. Allowedextensions.put ("File", Stringtoarraylist (Getinitparameter ("Allowedextensionsf  
        Ile ")));  
        Deniedextensions.put ("File", Stringtoarraylist (Getinitparameter ("Deniedextensionsfile"));  
        Allowedextensions.put ("Image", Stringtoarraylist (Getinitparameter ("Allowedextensionsimage"));  
        Deniedextensions.put ("Image", Stringtoarraylist (Getinitparameter ("Deniedextensionsimage"));  
        Allowedextensions.put ("Flash", Stringtoarraylist (Getinitparameter ("Allowedextensionsflash"));  
        Deniedextensions.put ("Flash", Stringtoarraylist (Getinitparameter ("Deniedextensionsflash")); if (Debug) System.out. println ("----simpleuploaderservlet initialization completed--  
    --\r\n ");  } public void Doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {doPost (requeSt, response); } public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception  
        , IOException {if (debug) System.out.println ("---BEGIN DOPOST---"); Response.setcontenttype ("text/html;  
        Charset=utf-8 ");  
        Response.setheader ("Cache-control", "No-cache");  
        PrintWriter out = Response.getwriter ();  
        Gets the type of upload file from the request parameter: File/image/flash String typestr = Request.getparameter ("type");  
        if (typestr = = null) {typestr = "File";  
        } if (Debug) System.out.println (TYPESTR);  
        Instantiates a Dnow object, gets the current time date Dnow = new Date ();  
        Set the upload file path String currentpath = baseDir + typestr + "/" + Dirformatter.format (dnow);  
        Get the upload path for the web App String Currentdirpath = Getservletcontext (). Getrealpath (Currentpath); Determines whether a folder exists, does not exist, creates a file dirtest = new File (Currentdirpath);  
        if (!dirtest.exists ()) {dirtest.mkdirs ();  
        }//Add the path before the Web app name Currentpath = Request.getcontextpath () + Currentpath;  
        if (Debug) System.out.println (Currentdirpath);  
        FileName and file true path String newName = "";  
        String fileUrl = ""; if (enabled) {//Use FileUpload in Apache Common component for file upload fileitemfactory factory = new Diskfileit  
            Emfactory ();  
            Servletfileupload upload = new Servletfileupload (factory);  
                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 ());  Else Fields.put (Item.getfieldname (), item);  
                }//Cekditor The name value of the file field is upload fileitem uplfile = (fileitem) fields.get ("Upload");  
                Get the file name and do the processing String Filenamelong = Uplfile.getname ();  
                Filenamelong = filenamelong.replace (' \ \ ', '/');  
                string[] Pathparts = Filenamelong.split ("/");  
                String fileName = pathparts[pathparts.length-1];  
                Gets the file name extension String ext = getextension (fileName);  
                Set the upload file name filename = Fileformatter.format (dnow) + "." + ext;  
                Get file name (no extension) String Namewithoutext = getnamewithoutextension (filename);  
                File Pathtosave = new file (Currentdirpath, fileName);  
                FILEURL = Currentpath + "/" + fileName; if (extisallowed (TYPESTR, ext)) {intcounter = 1;  
                        while (Pathtosave.exists ()) {newName = Namewithoutext + "_" + Counter + "." + ext;  
                        FILEURL = Currentpath + "/" + newName;  
                        Pathtosave = new File (Currentdirpath, newName);  
                    counter++;  
                } uplfile.write (Pathtosave);  
                } else {if (debug) System.out.println ("Invalid file type:" + ext);  
            }} catch (Exception ex) {if (debug) ex.printstacktrace ();  
        }} else {if (debug) System.out.println ("CKEditor upload function not enabled");  
        }//Ckeditorfuncnum is the position shown at the callback, this parameter must have String callback = Request.getparameter ("Ckeditorfuncnum");  
        Out.println ("<script type=\" text/javascript\ ">"); Out.println ("Window.parent.CKEDITOR.tools.callFunction ("+ Callback +", ' "+ FileUrl +" ', ' "+") ");  
        Out.println ("</script>");  
        Out.flush ();  
        Out.close ();  
    if (Debug) System.out.println ("---END DOPOST---"); }/** * method to get file name */private static string Getnamewithoutextension (string filename) {RET  
    Urn filename.substring (0, Filename.lastindexof (".")); }/** * method to get Extension */private string GetExtension (string fileName) {return filename.subst  
    Ring (Filename.lastindexof (".") + 1); }/** * String like ArrayList conversion method */Private ArrayList stringtoarraylist (String str) {if (Debu  
        g) System.out.println (str);  
        string[] Strarr = Str.split ("\\|");  
        ArrayList tmp = new ArrayList ();  
           if (str.length () > 0) {for (int i = 0; i < strarr.length; ++i) {if (debug)         SYSTEM.OUT.PRINTLN (i + "-" + strarr[i]);  
            Tmp.add (Strarr[i].tolowercase ());  
    }} return tmp; }/** * method to determine if extension is allowed */private Boolean extisallowed (String fileType, String ext) {Ext  
        = Ext.tolowercase ();  
        ArrayList allowlist = (ArrayList) allowedextensions.get (FileType);  
        ArrayList denylist = (ArrayList) deniedextensions.get (FileType);  
            if (allowlist.size () = = 0) {if (Denylist.contains (EXT)) {return false;  
            } else {return true; }} if (denylist.size () = = 0) {if (Allowlist.contains (EXT)) {return  
            True  
            } else {return false;  
    }} return false;  

 }  
}

As long as the upload property is set in the script in the page, we can see the Upload tab when we open the picture, after selecting the picture, click Upload to the server, uploading the success will automatically jump to the Image tab, you can see the source file already exists in the target directory of the server, at this time, We can edit the uploaded image in the editor, it is very convenient.

After submission, you can see that the data obtained is exactly the same, so using CKEditor to upload files has been successful.

We look at the source file and get the following results.

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >  

Problem: File is not uploaded correctly because there is no button to upload files on the toolbar




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.