[CKEditor that thing] using the Java Development CKEditor file upload function

Source: Internet
Author: User
Tags create directory dateformat file upload mkdir

On the use of CKEditor, there are countless articles on the web, no longer repeat here. And on the Java-supported file upload function, the network also has tens of thousands of articles, but the traversal of more than 10 20 will find that the same plagiarism, a variety of crawler programs brought about by the Internet information garbage to our information access to bring great obstacles. Those who use Java development ckeditor upload and file browsing functions, the same use is the servlet way, the traditional JSP model, no matter what the framework has been developed to what realm, are the same copy, plagiarism, people are very helpless, in fact, this is a very simple function, is to get the request, upload the file, return the result.

Usually our project uses SPRINGMVC or struts or other frameworks as part of C, in other words, controlling the request and execution process. And if we are using a spring or struts system, or to use the servlet configuration urlmapping to intercept file upload request, it is not very awkward, those who copy article, how do not think about it.

Back to the point, ckeditor default picture insertion, is not with the "Browse picture" and "upload" label, so need to manually configure, open this function, and the main trick, that is, the location of the configuration:

Picture upload configuration Config.filebrowseruploadurl = ' upload.do?type=file '; Config.filebrowserimageuploadurl = ' upload.do?type=image '; Config.filebrowserflashuploadurl = ' Upload.do?type=flash '; Picture browsing Configuration Config.filebrowserimagebrowseurl = ' browerserver.do?type=image ';

We have configured the path above, since CKEditor does not have Java-enabled Plug-ins, so here is what we need to develop ourselves. The above upload and browse pictures of the request, we define their own URL, that is, the above. Do end of the section, my test project is used in Springmvc, using the annotation function after 2.5.

OK, here's the configuration, so what's the function? Open CKEditor:

Can see that the above more than upload and browsing function, now Click is useless, because we have not developed a specific implementation

So what is the effect of those two places that have been deployed? Using Firefox to see the code for the upload section, it's obvious what the URL of that configuration is for.

In fact, is an upload form, that action URL is our configuration, so as long as the development of interception of this request and upload the file function is OK, how simple things.

Before writing the code, look at our status quo, we may let this image upload to the image server, however, there is not enough money in the pocket, and this picture is not small, so at this stage is still kept in the application of specific positions, enough helpless, no way, who let me have a specific picture server it, Then the way in this application under the article. We use a upload/img directory, to save picture files, later to migrate to the picture server is also easier.

But the problem is, all the pictures are in this folder, it is not very large, and once more than 1000, file search speed is a bit tortured, then I want to find a way, then set up a level of directory, each level below the maximum 500, if the current folder more than 500, Re-establish a folder and put it in. So the catalog becomes the level three upload/img/20100824 we use the time string to name it.

Let's look at the code:

Package com.normandy.position.web; Import Java.io.File; Import java.io.IOException; Import Java.io.PrintWriter; Import Java.text.DateFormat; Import java.text.ParseException; Import Java.text.SimpleDateFormat; Import Java.util.Date; Import Java.util.Iterator; Import java.util.List; Import Javax.servlet.http.HttpServletRequest; Import Javax.servlet.http.HttpServletResponse; Import Org.apache.commons.fileupload.FileItem; Import Org.apache.commons.fileupload.FileItemFactory; Import org.apache.commons.fileupload.FileUploadException; Import Org.apache.commons.fileupload.disk.DiskFileItemFactory; Import Org.apache.commons.fileupload.servlet.ServletFileUpload; Import Org.apache.commons.lang.StringUtils; Import Org.apache.commons.lang.time.DateUtils; Import Org.apache.log4j.Logger; Import Org.springframework.stereotype.Controller; Import Org.springframework.ui.ModelMap; Import org.springframework.web.bind.annotation.RequestMapping; Import Org.springframework.web.bind.annotation.RequestMethod; /* * * Upload image * <p> * for ckeditor custom image upload function, the following can be extended upload other formats file * uploaded files of the base path: ${apache.home}/${project.name}/${project.name }/freemarker/upload/img/${' YYYYMMDD '}/* Maximum of 500 files per folder * </p> * @author Mikko * * */@Controller @RequestMapping ("/u Pload.do ") public class Fileuploadcontroller {protected final Logger Logger = Logger. GetLogger (Fileuploadcontroller.cla SS); /** ~ ~ ~ ~ Upload File Save path * * Private static final String File_upload_dir = "/upload"; /** ~ ~ ~ ~ ~ Upload the file to save the next level of path, labeled storage type * * Private static final String File_upload_sub_img_dir = "/img"; /** ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ to allow CKEditor load to upload the picture, the position is limited under the Freemarker/private static final String For_freemarker_load_dir = "/freemarker" ; /** ~ ~ ~ The maximum number of files saved per upload subdirectory * * private static final int max_num_per_upload_sub_dir = 500; /** ~ ~ ~ ~ Upload file Maximum file size * * Private static final long max_file_size = 1024 * 1024 * 2; /** ~ ~ ~ ~ system defaults to establish and use time string as the file name of the time format * * private static final String Default_sub_folder_format_auto = "YYYYMMDD"; /** ~ ~ ~ here to expand the format, to prevent the manual establishment of the not unified * * private static final String DEFault_sub_folder_format_no_auto = "YYYY-MM-DD"; @RequestMapping (method = Requestmethod.get) is public void Processupload (Modelmap modelmap, httpservletrequest request, HttpServletResponse response) {Processuploadpost (Modelmap, request, response); return;} @RequestMapping requestmethod.post) public void Processuploadpost (Modelmap modelmap, httpservletrequest request, HttpServletResponse Response) {//Judge whether the submitted request contains a file Boolean Ismultipart = servletfileupload.ismultipartcontent (request); if (!ismultipart) {RET Urn //Get directory File Floder = buildfolder (request); if (null = = Floder) {return;} try {response.setcontenttype ("text/html; Charset=utf-8 "); Response.setheader ("Cache-control", "No-cache"); PrintWriter out = Response.getwriter (); The return address of the uploaded file String fileUrl = ""; Fileitemfactory factory = new Diskfileitemfactory (); Servletfileupload servletfileupload = new Servletfileupload (factory); Servletfileupload.setfilesizemax (max_file_size); @SuppressWarnings ("unchecked") List<fileitem> Fileitem = servletfileupload.parserequest (request); if (null = = Fileitem | | 0 = fileitem.size ()) {return;} iterator<fileitem> Fileitemindex = Fileitem.iterator (); if (Fileitemindex.hasnext ()) {Fileitem file = Fileitemindex.next (); if (File.isformfield ()) {Logger.error ("illegal uploading of files.") Isformfield=true "); String fileclientname = GetFileName (File.getname ()); String Filefix = stringutils.substring (Fileclientname, Fileclientname.lastindexof (".") + 1); if (! Stringutils.equalsignorecase (filefix, "jpg") &&! Stringutils.equalsignorecase (Filefix, "JPEG") &&! Stringutils.equalsignorecase (Filefix, "BMP") &&! Stringutils.equalsignorecase (Filefix, "GIF") &&! Stringutils.equalsignorecase (Filefix, "png")) {Logger.error ("Incorrect format of upload file =" + Filefix); return;} if ( Logger.isinfoenabled ()) {Logger.info ("Start uploading file:" + file.getname ());} For the client has already set the picture name in the server to continue to be able to clearly identify, here does not change the name file NewFile = new file (Floder, fileclientname); File.write (NewFile); if (logger.isinfoenabled (){logger.info ("Upload file end, new name:" + Fileclientname + ". Floder:" + Newfile.getpath ());} Assemble return URL to facilitate ckeditor positioning picture FileUrl = For_freemarker_load_dir + file_upload_dir + file_upload_sub_img_dir + File.separator+floder.getname () + File.separator + newfile.getname (); FILEURL = fileurl.substring (1);//Remove/freemarker first/, otherwise ckeditor not recognize FILEURL = Stringutils.replace (FILEURL, "//", "/"); Returns the URL of the uploaded picture to CKEditor String callback = Request.getparameter ("Ckeditorfuncnum"); Out.println ("<mce:script type=/" text/javascript/"><!--"); Out.println ("window.parent.CKEDITOR.tools.callFunction (" + Callback + ", '" + FileUrl + "," "+") "); OUT.PRINTLN ("//--></mce:script>"); } out.flush (); Out.close (); catch (IOException e) {logger.error ("The upload file has an exception. ", e);} catch (Fileuploadexception e) {logger.error ("The upload file has an exception.) ", e);} catch (Exception e) {logger.error ("The upload file has an exception.) ", e);} Return /** * Get file name * @param str * @return/private string GetFileName (String str) {int index = Str.lastindexof ("//"); if ( -1!= index) {return str.substring (index);} else {return str;}} /** * Create directory * * @return/private File Buildfolder (HttpServletRequest request) {//here to take care of CKEditor, due to the FTL placement of the reason, here must be in free The marker directory can be loaded into the picture, otherwise it can be uploaded and used normally, but//cannot operate normally in the control String Realpath = Request.getsession (). Getservletcontext (). Getrealpath (For_freemarker_load_dir); Logger.error (Realpath); First level directory, if not present, create file Firstfolder = new file (Realpath + file_upload_dir); if (!firstfolder.exists ()) {if (!firstfolder.mkdir ()) {return null;}}//Level two directory, if not present, create String Folderdir = Realpath + F Ile_upload_dir + File_upload_sub_img_dir; if (logger.isdebugenabled ()) {Logger.debug ("Folderdir" + Folderdir);} if (Stringutils.isblank (Folderdir)) { Logger.error ("Path error:" + Folderdir); return null; } File Floder = new file (Folderdir); if (!floder.exists ()) {if (!floder.mkdir ()) {Logger.error ("Error creating folder. Path= "+ folderdir); return null; }//Down folder is named after the time string, so get the latest time folder can string[] files = floder.list (); if (Null!= files &Amp;& 0 < Files.length) {//contains subfolders, gets the latest date olddate = null; int index =-1; for (int i = 0; i < Files.lengt H i++) {String fileName = Files[i]; try {Date thisdate = dateutils.parsedate (FileName, new string[] {default_sub_folder_f Ormat_auto, Default_sub_folder_format_no_auto}); if (olddate = = null) {olddate = thisdate; index = i;} else {if (Thisdate.after (olddate)) {//Save the latest time and subscript olddate in the array = Thisdate; index = i; The catch (ParseException e) {//here is abnormal to eat, do not do anything, if the resolution fails, will create a new folder, to prevent the artificial creation of the folder caused by the exception. }//for//To determine if the maximum number of pictures already exists under the currently current folder (Null!= olddate &&-1!= index) {file Pointfloder = new file (folderdir + File.separator + files[index]); if (!pointfloder.exists ()) {if (!pointfloder.mkdir ()) {Logger.error ("Error creating folder. Path= "+ folderdir); return null; }//If the file under the folder exceeds the maximum value, you will need to create a new folder string[] Pointfloderfiles = Pointfloder.list (); if (null!= pointfloderfiles && Max_num_per_upload_sub_dir < pointfloderfiles.length) {return Buildnewfile ( FoldeRDIR); return pointfloder; ///Find the current subfolder failed, create a new return Buildnewfile (Folderdir); else {//does not contain subfolders, create a new one, usually the system first upload will have this situation return Buildnewfile (Folderdir);} /** * Create a new file * @param path * @return/Private file Buildnewfile (String path) {//no subfolders, new one, usually the first time the system is uploaded file Newfi Le = buildfilebysystime (path); if (null = = NewFile) {logger.error ("Create folder failed.") newfile= "+ newFile); return newFile; /** * Create a folder based on the current time format YYYYMMDD * * @param path * @return/private File Buildfilebysystime (String path) {DateFormat d f = new SimpleDateFormat (Default_sub_folder_format_auto); String fileName = Df.format (New Date ()); File File = new file (path + file.separator + fileName); if (!file.mkdir ()) {return null;} return file; } }

Here I use the annotation @controller, if you are using struts, then configure an action bar, are very simple things ...

Just a little bit more, if you use this way to develop, and then go to run in the eclipse, you will find the upload is not an error, but the return URL does not show the picture at all, what's going on?

In this case, there is a server display box under Eclipse, double-click the server you created, you can configure the server's startup path, and so on, one of the options that needs our special attention:

When the project is released in the future, if you copy the project directly to Tomcat, there is no problem, but the testing phase is more convenient, is here to change the deployment path, etc., so that our upload function with the same as the online after the entry into force.

The above upload log will print out:

D:/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp2/wtpwebapps/normandyposition/freemarker/upload /img/20100824/logo.jpg

Compared to the content of the above, is not you also understand what is going on, the above is actually a temporary directory, so here we want to change:

To change server path to your Apache installation directory, you can select the second radio button directly

Change deploy path to your project name

After the change is done:

It's done.

The next chapter I think how to get a multi-level directory of the server's image browsing function

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.