ckeditor to increase in the jsp image upload function (2)

Before writing the article explains how to manually open the ckeditor in jsp image upload, but after all, write your own upload interface is really ugly. More search information, find that there are better and more simple way.

Before the reference @ 126/blog/static/890531092010226023136 / and
Are trying to open ckeditor default image upload, but failed to successfully uploaded into the background, this may be due to their callback function call error.

Thank the author, his most simple and beautiful way, but also solve the fundamental problem.

ckeditor to increase in the jsp image upload function (2)

ckeditor to increase in the jsp image upload function (2)

ckeditor to increase in the jsp image upload function (2)

Summarized under the upload feature is very simple in fact open, front only the following code:

// This is followed by the parameters are to upload files, pictures, and  flash
                        CKEDITOR.replace( 'context',{filebrowserUploadUrl : '',
                                filebrowserImageUploadUrl : '',
                                filebrowserFlashUploadUrl : ''

Background components can be apache commons io package in to upload fileupload and operation simple to use struts1.2 write back, the bag comes with the lack of attention struts1.2 ways to add an attachment package.

package info.hellolihui.action;

import java.util.Date;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

public class CKUploadAction extends DispatchAction {

        //  Allows you to upload the file extensions
        private final String[] exts = new String[]{"gif","png","jpeg","jpg","bmp"}; 

        public ActionForward unspecified(ActionMapping mapping, ActionForm form,
                        HttpServletRequest request, HttpServletResponse response)
                        throws Exception {
                System.out.println("  Upload  ");

                ServletContext servletContext = request.getSession().getServletContext();

                //   Upload file path set
                String path = servletContext.getRealPath("/upload") + "/";

                String typeStr = request.getParameter("type");
                //  If the type is empty, the default file to upload
        if (typeStr == null) {
            typeStr = "file";
        path += typeStr;

        //   Determine whether the folder exists, does not exist, create  ,  At this point the path with the file name has not been  ,  As  Format
        File dirTest = new File(path);
        if (!dirTest.exists()) {


        //  Use Apache Common component  fileupload  Upload files
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);   

        //   True path of the file name and file
        String newName = "";
        String fileUrl = "";
        String fileName = ""; //  Only the file name
        try {
            List items = upload.parseRequest(request);
            Map fields = new HashMap();
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem);
                if (item.isFormField())
                    fields.put(item.getFieldName(), item.getString());
                    fields.put(item.getFieldName(), item);
            // CEKditor  In the file domain  name  Value is  upload
            FileItem uplFile = (FileItem) fields.get("upload");
            //   Get the file name and do the deal
            String fileNameLong = uplFile.getName();
            fileNameLong = fileNameLong.replace('\\', '/');
            String[] pathParts = fileNameLong.split("/");
            fileName = pathParts[pathParts.length - 1];
            //   Get the file extension
            String ext = getExtension(fileName);
            //   Set upload file names to the time named
            fileName = new Date().getTime() + "." + ext;
            //   Get the file name  (  No extension  )
            String nameWithoutExt = getNameWithoutExtension(fileName);
            File pathToSave = new File(path, fileName);
            fileUrl = path + "/" + fileName;
            if (extIsAllowed(ext)) {
                int counter = 1;
                while (pathToSave.exists()) {
                    newName = nameWithoutExt + "_" + counter + "." + ext;
                    fileUrl = path + "/" + newName;
                    pathToSave = new File(path, newName);
            } else {
                System.out.println("  Invalid file type  : " + ext);
        }catch (Exception ex) {
        PrintWriter out = response.getWriter();   

        // CKEditorFuncNum  Is displayed when the location of the callback, this parameter must be
        //  Does not exist  d:\  The address, to  url
                String url = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/upload/" + typeStr + "/" + fileName;
        String callback = request.getParameter("CKEditorFuncNum");
        out.println("<script type=\"text/javascript\">");
        out.println("" + callback
                + ",'" + url + "',''" + ")");

                return null;


         *   Way to get the file name
        private static String getNameWithoutExtension(String fileName) {
                return fileName.substring(0, fileName.lastIndexOf("."));

         *   Method for extension
        private String getExtension(String fileName) {
                return fileName.substring(fileName.lastIndexOf(".") + 1);

         *   To determine whether to allow the method of extension
        private boolean extIsAllowed(String ext) {
                ext = ext.toLowerCase();
                List extList = Arrays.asList(this.exts);
                return extList.contains(ext)?true:false;


分类:Web 时间:2010-08-31 人气:261
blog comments powered by Disqus


  • java achieve excel import and export (2) (transfer) 2010-05-02

    ================= ===================== Summary java how to do Excel (data import and export) (change) jxl.jar, can go to download. 1. To read the contents of Excel files java code / ** Read

  • java achieve excel import export (1) (transfer) 2010-05-02

    Java data into Excel package com.bossy.base; import; import; import; import; import java.util.ArrayList; import java.util.List; import jxl.Workbook; import jxl.format.U

  • Java Oracle Blob import and export Word 2010-12-10

    import; import; import; import; import; import; import; import; impor

  • Java code mysql import and export 2011-08-12

    Note mysql import and export must be prepared to achieve good environmental variables, such as: C: \ Program Files \ MySQL \ MySQL Server 5.1 \ bin; otherwise it will not work correctly. package cc.javaweb; import; import java.

  • XML switch to Java Java to switch XML 2010-03-29

    mport ibatis.Person; import; import; /** * XML Go Java */ public class ReadExampleApp { public static final void main(String args[]) throws Exception { // Create a stream to read the XML f

  • DWR understanding of DATA (or call back List.Set Ways Map of java) 2009-05-24

    Call Return List, Set or Map of the java method 1, dwr.xml configuration Configuration with 4.1 <dwr> <allow> <create creator="new" javascript="testClass" > <param name="class" value="com.dwr.TestCla

  • Flex integration of JAVA, JAVA returned from a XML file, then the datagrid values FLEX 2010-09-16

    Project. I FLEX page to access a JSP page called from the JSP page to get a XML. I have to the collection of the datagrid display in the FLEX approach. The following is the code of my LogFlex <? Xml version = "1.0" encoding = "utf-8"

  • [MongoDB for Java]Java操作MongoDB 2013-05-15

    开发环境: System:Windows IDE:eclipse.MyEclipse 8 Database:mongoDB 开发依赖库: JavaEE5.mongo-2.5.3.jar.junit-4.8.2.jar Blog: 一.准备工作 1. 首先,下载mongoDB对Java支持的驱动包 驱动包下载地址:https://github.c

  • 2014-07-09 Java Web的学习(6)-----JSP和EL 2014-07-17

    1.什么是JSP JSP全称是Java Server Pages,它和servle技术一样,都是SUN公司定义的一种用于开发动态web资源的技术.JSP/Servlet规范.JSP实际上就是Servlet. JSP这门技术的最大的特点在于,写jsp就像在写html,但它相比html而言,html只能为用户提供静态数据,而Jsp技术允许在页面中嵌套java代码,为用户提供动态数据. 2.JSP调用和运行原理 1.当你访问web服务器中的JavaWeb应用时,如果访问的不是一个Servlet,那么都

  • java java rounding and rounding method 2010-12-31

    import java.math.BigDecimal; import java.text.DecimalFormat; public class TestGetInt{ public static void main(String[] args){ double i=2, j=2.1, k=2.5, m=2.9; System.out.println(" Round off the decimal rounding :Math.floor(2)=" + (int)Math.floor

iOS 开发

Android 开发

Python 开发



PHP 开发

Ruby 开发






Javascript 开发

.NET 开发



Copyright (C), All Rights Reserved. 版权所有 闽ICP备15018612号

processed in 0.034 (s). 13 q(s)