FCKeditor的详细配置

1,下载FCKeditor 2.6.3
2,下载fckeditor-java-2.4.1-bin.zip
3,下载fckeditor-java-demo-2.4.1.war (可作为参考)

第一步是fckeditor使用配置文件
在FCKeditor文件夹里新建一个myconfig.js(它可覆盖fckconfig.js 的配置)
以后可根据实际的需要来配置

第二部是文件上传的配置
FCKeditor默认是不支持文件上传的,需要我们手动配置
1,在web.xml 输入

Java代码 复制代码
  1. <servlet>   
  2.       <servlet-name>Connector</servlet-name>   
  3.         <servlet-class>   
  4.           net.fckeditor.connector.ConnectorServlet   
  5.       </servlet-class>   
  6.       <load-on-startup>1</load-on-startup>   
  7.     </servlet>   
  8.     ...   
  9.     <servlet-mapping>   
  10.       <servlet-name>Connector</servlet-name>   
  11.       <url-pattern>   
  12.         /fckeditor/editor/filemanager/connectors/*   
  13.       </url-pattern>   
  14.     </servlet-mapping>  
<servlet>
      <servlet-name>Connector</servlet-name>
        <servlet-class>
          net.fckeditor.connector.ConnectorServlet
      </servlet-class>
      <load-on-startup>1</load-on-startup>
    </servlet>
    ...
    <servlet-mapping>
      <servlet-name>Connector</servlet-name>
      <url-pattern>
        /fckeditor/editor/filemanager/connectors/*
      </url-pattern>
    </servlet-mapping>


2,新建一个 fckeditor.properties 文件 in your classpath :
输入

Java代码 复制代码
  1. connector.userActionImpl=net.fckeditor.requestcycle.impl.UserActionImpl  
connector.userActionImpl=net.fckeditor.requestcycle.impl.UserActionImpl



第三步是解决上传中文乱码的问题
我们新建一个类 比如 com.fck.fckeditor.ConnectorServlet

Java代码 复制代码
  1. package com.fck.fckeditor;   
  2.   
  3. /*  
  4.  * FCKeditor - The text editor for Internet - http://www.fckeditor.net  
  5.  * Copyright (C) 2003-2008 Frederico Caldeira Knabben  
  6.  *   
  7.  * == BEGIN LICENSE ==  
  8.  *   
  9.  * Licensed under the terms of any of the following licenses at your  
  10.  * choice:  
  11.  *   
  12.  *  - GNU General Public License Version 2 or later (the "GPL")  
  13.  *    http://www.gnu.org/licenses/gpl.html  
  14.  *   
  15.  *  - GNU Lesser General Public License Version 2.1 or later (the "LGPL")  
  16.  *    http://www.gnu.org/licenses/lgpl.html  
  17.  *   
  18.  *  - Mozilla Public License Version 1.1 or later (the "MPL")  
  19.  *    http://www.mozilla.org/MPL/MPL-1.1.html  
  20.  *   
  21.  * == END LICENSE ==  
  22.  */  
  23.   
  24.   
  25. import java.io.File;   
  26. import java.io.IOException;   
  27. import java.io.PrintWriter;   
  28. import java.util.List;   
  29. import java.util.UUID;   
  30.   
  31. import javax.servlet.ServletException;   
  32. import javax.servlet.http.HttpServlet;   
  33. import javax.servlet.http.HttpServletRequest;   
  34. import javax.servlet.http.HttpServletResponse;   
  35.   
  36. import net.fckeditor.connector.Messages;   
  37. import net.fckeditor.handlers.CommandHandler;   
  38. import net.fckeditor.handlers.ConnectorHandler;   
  39. import net.fckeditor.handlers.ExtensionsHandler;   
  40. import net.fckeditor.handlers.RequestCycleHandler;   
  41. import net.fckeditor.handlers.ResourceTypeHandler;   
  42. import net.fckeditor.response.UploadResponse;   
  43. import net.fckeditor.response.XmlResponse;   
  44. import net.fckeditor.tool.Utils;   
  45. import net.fckeditor.tool.UtilsFile;   
  46. import net.fckeditor.tool.UtilsResponse;   
  47.   
  48. import org.apache.commons.fileupload.FileItem;   
  49. import org.apache.commons.fileupload.FileItemFactory;   
  50. import org.apache.commons.fileupload.disk.DiskFileItemFactory;   
  51. import org.apache.commons.fileupload.servlet.ServletFileUpload;   
  52. import org.apache.commons.io.FilenameUtils;   
  53. import org.slf4j.Logger;   
  54. import org.slf4j.LoggerFactory;   
  55.   
  56. /**  
  57.  * Servlet to upload and browse files.<br />  
  58.  *   
  59.  * This servlet accepts 4 commands which interact with the server-side  
  60.  * filesystem.<br />  
  61.  * The allowed commands are:  
  62.  * <ul>  
  63.  * <li><code>GetFolders</code>: Retrieves a list of folders in the current  
  64.  * folder</li>  
  65.  * <li><code>GetFoldersAndFiles</code>: Retrives a list of files and folders  
  66.  * in the current folder</li>  
  67.  * <li><code>CreateFolder</code>: Creates a new folder in the current folder</li>  
  68.  * <li><code>FileUpload</code>: Stores an uploaded file into the current  
  69.  * folder. (must be sent with POST)</li>  
  70.  * </ul>  
  71.  *   
  72.  * @version $Id: ConnectorServlet.java 2101 2008-06-22 22:00:48Z mosipov $  
  73.  */  
  74. public class ConnectorServlet extends HttpServlet {   
  75.   
  76.     private static final long serialVersionUID = -5742008970929377161L;   
  77.     private static final Logger logger = LoggerFactory.getLogger(ConnectorServlet.class);   
  78.   
  79.     /**  
  80.      * Initialize the servlet: <code>mkdir</code> &lt;DefaultUserFilesPath&gt;  
  81.      */  
  82.     public void init() throws ServletException, IllegalArgumentException {   
  83.         String realDefaultUserFilesPath = getServletContext().getRealPath(   
  84.                 ConnectorHandler.getDefaultUserFilesPath());   
  85.   
  86.         File defaultUserFilesDir = new File(realDefaultUserFilesPath);   
  87.         UtilsFile.checkDirAndCreate(defaultUserFilesDir);   
  88.   
  89.         logger.info("ConnectorServlet successfully initialized!");   
  90.     }   
  91.   
  92.     /**  
  93.      * Manage the <code>GET</code> requests (<code>GetFolders</code>,  
  94.      * <code>GetFoldersAndFiles</code>, <code>CreateFolder</code>).<br/>  
  95.      *   
  96.      * The servlet accepts commands sent in the following format:<br/>  
  97.      * <code>connector?Command=&lt;CommandName&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>  
  98.      * <p>  
  99.      * It executes the commands and then returns the result to the client in XML  
  100.      * format.  
  101.      * </p>  
  102.      */  
  103.     public void doGet(HttpServletRequest request, HttpServletResponse response)   
  104.             throws ServletException, IOException {   
  105.         logger.debug("Entering ConnectorServlet#doGet");   
  106.   
  107.         response.setCharacterEncoding("UTF-8");   
  108.         response.setContentType("application/xml; charset=UTF-8");   
  109.         response.setHeader("Cache-Control""no-cache");   
  110.         PrintWriter out = response.getWriter();   
  111.   
  112.         String commandStr = request.getParameter("Command");   
  113.         String typeStr = request.getParameter("Type");   
  114.         String currentFolderStr = request.getParameter("CurrentFolder");   
  115.   
  116.         logger.debug("Parameter Command: {}", commandStr);   
  117.         logger.debug("Parameter Type: {}", typeStr);   
  118.         logger.debug("Parameter CurrentFolder: {}", currentFolderStr);   
  119.   
  120.         XmlResponse xr;   
  121.   
  122.         if (!RequestCycleHandler.isEnabledForFileBrowsing(request))   
  123.             xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.NOT_AUTHORIZED_FOR_BROWSING);   
  124.         else if (!CommandHandler.isValidForGet(commandStr))   
  125.             xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_COMMAND);   
  126.         else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))   
  127.             xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_TYPE);   
  128.         else if (!UtilsFile.isValidPath(currentFolderStr))   
  129.             xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_CURRENT_FOLDER);   
  130.         else {   
  131.             CommandHandler command = CommandHandler.getCommand(commandStr);   
  132.             ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);   
  133.   
  134.             String typePath = UtilsFile.constructServerSidePath(request, resourceType);   
  135.             String typeDirPath = getServletContext().getRealPath(typePath);   
  136.   
  137.             File typeDir = new File(typeDirPath);   
  138.             UtilsFile.checkDirAndCreate(typeDir);   
  139.   
  140.             File currentDir = new File(typeDir, currentFolderStr);   
  141.   
  142.             if (!currentDir.exists())   
  143.                 xr = new XmlResponse(XmlResponse.EN_INVALID_FOLDER_NAME);   
  144.             else {   
  145.   
  146.                 xr = new XmlResponse(command, resourceType, currentFolderStr, UtilsResponse   
  147.                         .constructResponseUrl(request, resourceType, currentFolderStr, true,   
  148.                                 ConnectorHandler.isFullUrl()));   
  149.   
  150.                 if (command.equals(CommandHandler.GET_FOLDERS))   
  151.                     xr.setFolders(currentDir);   
  152.                 else if (command.equals(CommandHandler.GET_FOLDERS_AND_FILES))   
  153.                     xr.setFoldersAndFiles(currentDir);   
  154.                 else if (command.equals(CommandHandler.CREATE_FOLDER)) {   
  155.                        
  156.                     //修改新建文件夹中文乱码   
  157.                        
  158.                      String temStr= request.getParameter("NewFolderName");   
  159.                     temStr=new String(temStr.getBytes("iso8859-1"),"utf-8");   
  160.                     // 完毕   
  161.                        
  162.                     String newFolderStr = UtilsFile.sanitizeFolderName(temStr);   
  163.                     logger.debug("Parameter NewFolderName: {}", newFolderStr);   
  164.   
  165.                     File newFolder = new File(currentDir, newFolderStr);   
  166.                     int errorNumber = XmlResponse.EN_UKNOWN;   
  167.   
  168.                     if (newFolder.exists())   
  169.                         errorNumber = XmlResponse.EN_ALREADY_EXISTS;   
  170.                     else {   
  171.                         try {   
  172.                             errorNumber = (newFolder.mkdir()) ? XmlResponse.EN_OK   
  173.                                     : XmlResponse.EN_INVALID_FOLDER_NAME;   
  174.                         } catch (SecurityException e) {   
  175.                             errorNumber = XmlResponse.EN_SECURITY_ERROR;   
  176.                         }   
  177.                     }   
  178.                     xr.setError(errorNumber);   
  179.                 }   
  180.             }   
  181.         }   
  182.   
  183.         out.print(xr);   
  184.         out.flush();   
  185.         out.close();   
  186.         logger.debug("Exiting ConnectorServlet#doGet");   
  187.     }   
  188.   
  189.     /**  
  190.      * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />  
  191.      *   
  192.      * The servlet accepts commands sent in the following format:<br />  
  193.      * <code>connector?Command=&lt;FileUpload&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>  
  194.      * with the file in the <code>POST</code> body.<br />  
  195.      * <br>  
  196.      * It stores an uploaded file (renames a file if another exists with the  
  197.      * same name) and then returns the JavaScript callback.  
  198.      */  
  199.     @SuppressWarnings("unchecked")   
  200.     public void doPost(HttpServletRequest request, HttpServletResponse response)   
  201.             throws ServletException, IOException {   
  202.         logger.debug("Entering Connector#doPost");   
  203.   
  204.         response.setCharacterEncoding("UTF-8");   
  205.         response.setContentType("text/html; charset=UTF-8");   
  206.         response.setHeader("Cache-Control""no-cache");   
  207.         PrintWriter out = response.getWriter();   
  208.   
  209.         String commandStr = request.getParameter("Command");   
  210.         String typeStr = request.getParameter("Type");   
  211.         String currentFolderStr = request.getParameter("CurrentFolder");   
  212.   
  213.         logger.debug("Parameter Command: {}", commandStr);   
  214.         logger.debug("Parameter Type: {}", typeStr);   
  215.         logger.debug("Parameter CurrentFolder: {}", currentFolderStr);   
  216.   
  217.         UploadResponse ur;   
  218.   
  219.         // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'   
  220.         // are empty   
  221.         if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) {   
  222.             commandStr = "QuickUpload";   
  223.             currentFolderStr = "/";   
  224.         }   
  225.   
  226.         if (!RequestCycleHandler.isEnabledForFileUpload(request))   
  227.             ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, nullnull,   
  228.                     Messages.NOT_AUTHORIZED_FOR_UPLOAD);   
  229.         else if (!CommandHandler.isValidForPost(commandStr))   
  230.             ur = new UploadResponse(UploadResponse.SC_ERROR, nullnull, Messages.INVALID_COMMAND);   
  231.         else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))   
  232.             ur = new UploadResponse(UploadResponse.SC_ERROR, nullnull, Messages.INVALID_TYPE);   
  233.         else if (!UtilsFile.isValidPath(currentFolderStr))   
  234.             ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;   
  235.         else {   
  236.             ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);   
  237.   
  238.             String typePath = UtilsFile.constructServerSidePath(request, resourceType);   
  239.             String typeDirPath = getServletContext().getRealPath(typePath);   
  240.   
  241.             File typeDir = new File(typeDirPath);   
  242.             UtilsFile.checkDirAndCreate(typeDir);   
  243.   
  244.             File currentDir = new File(typeDir, currentFolderStr);   
  245.   
  246.             if (!currentDir.exists())   
  247.                 ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;   
  248.             else {   
  249.   
  250.                 String newFilename = null;   
  251.                 FileItemFactory factory = new DiskFileItemFactory();   
  252.                 ServletFileUpload upload = new ServletFileUpload(factory);   
  253.             // 修改上传中文名乱码   
  254.                 upload.setHeaderEncoding("UTF-8");   
  255.                 //  完毕   
  256.                 try {   
  257.   
  258.                     List<FileItem> items = upload.parseRequest(request);   
  259.   
  260.                     // We upload only one file at the same time   
  261.                     FileItem uplFile = items.get(0);   
  262.                     String rawName = UtilsFile.sanitizeFileName(uplFile.getName());   
  263.                     String filename = FilenameUtils.getName(rawName);   
  264.                     String baseName = FilenameUtils.removeExtension(filename);   
  265.                     String extension = FilenameUtils.getExtension(filename);   
  266.                        
  267.                     //修改上传文件名字,用UUID方法   
  268.                     filename=UUID.randomUUID().toString()+ "."+ extension;   
  269.                     //  完毕   
  270.                        
  271.                        
  272.                        
  273.                        
  274.                        
  275.                        
  276.                     //添加限制上传大小方法   
  277.                     //如果这个文件的扩展名不允许上传   
  278.                        
  279.                     if (!ExtensionsHandler.isAllowed(resourceType, extension))   
  280.                         ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);   
  281.                        
  282.                     //如果超出大小10M   
  283.                     else if(uplFile.getSize()> 10000 * 1024)    
  284.                     //传递一个自定义的错误码   
  285.                         ur = new UploadResponse(204);   
  286.                        
  287.                     // 如果不存在以上情况,则保存   
  288.                     else {   
  289.   
  290.                         // construct an unique file name   
  291.                         File pathToSave = new File(currentDir, filename);   
  292.                            
  293.                            
  294.                            
  295.                            
  296.                            
  297.                            
  298.                         int counter = 1;   
  299.                         while (pathToSave.exists()) {   
  300.                             newFilename = baseName.concat("(").concat(String.valueOf(counter))   
  301.                                     .concat(")").concat(".").concat(extension);   
  302.                             pathToSave = new File(currentDir, newFilename);   
  303.                             counter++;   
  304.                         }   
  305.   
  306.                         if (Utils.isEmpty(newFilename))   
  307.                             ur = new UploadResponse(UploadResponse.SC_OK, UtilsResponse   
  308.                                     .constructResponseUrl(request, resourceType, currentFolderStr,   
  309.                                             true, ConnectorHandler.isFullUrl()).concat(filename));   
  310.                         else  
  311.                             ur = new UploadResponse(UploadResponse.SC_RENAMED,   
  312.                                     UtilsResponse.constructResponseUrl(request, resourceType,   
  313.                                             currentFolderStr, true, ConnectorHandler.isFullUrl())   
  314.                                             .concat(newFilename), newFilename);   
  315.   
  316.                         // secure image check   
  317.                         if (resourceType.equals(ResourceTypeHandler.IMAGE)   
  318.                                 && ConnectorHandler.isSecureImageUploads()) {   
  319.                             if (UtilsFile.isImage(uplFile.getInputStream()))   
  320.                                 uplFile.write(pathToSave);   
  321.                             else {   
  322.                                 uplFile.delete();   
  323.                                 ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);   
  324.                             }   
  325.                         } else  
  326.                             uplFile.write(pathToSave);   
  327.   
  328.                     }   
  329.                 } catch (Exception e) {   
  330.                     ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);   
  331.                 }   
  332.             }   
  333.   
  334.         }   
  335.   
  336.         out.print(ur);   
  337.         out.flush();   
  338.         out.close();   
  339.   
  340.         logger.debug("Exiting Connector#doPost");   
  341.     }   
  342.   
  343. }  
package com.fck.fckeditor;

/*
 * FCKeditor - The text editor for Internet - http://www.fckeditor.net
 * Copyright (C) 2003-2008 Frederico Caldeira Knabben
 * 
 * == BEGIN LICENSE ==
 * 
 * Licensed under the terms of any of the following licenses at your
 * choice:
 * 
 *  - GNU General Public License Version 2 or later (the "GPL")
 *    http://www.gnu.org/licenses/gpl.html
 * 
 *  - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
 *    http://www.gnu.org/licenses/lgpl.html
 * 
 *  - Mozilla Public License Version 1.1 or later (the "MPL")
 *    http://www.mozilla.org/MPL/MPL-1.1.html
 * 
 * == END LICENSE ==
 */


import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.fckeditor.connector.Messages;
import net.fckeditor.handlers.CommandHandler;
import net.fckeditor.handlers.ConnectorHandler;
import net.fckeditor.handlers.ExtensionsHandler;
import net.fckeditor.handlers.RequestCycleHandler;
import net.fckeditor.handlers.ResourceTypeHandler;
import net.fckeditor.response.UploadResponse;
import net.fckeditor.response.XmlResponse;
import net.fckeditor.tool.Utils;
import net.fckeditor.tool.UtilsFile;
import net.fckeditor.tool.UtilsResponse;

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.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Servlet to upload and browse files.<br />
 * 
 * This servlet accepts 4 commands which interact with the server-side
 * filesystem.<br />
 * The allowed commands are:
 * <ul>
 * <li><code>GetFolders</code>: Retrieves a list of folders in the current
 * folder</li>
 * <li><code>GetFoldersAndFiles</code>: Retrives a list of files and folders
 * in the current folder</li>
 * <li><code>CreateFolder</code>: Creates a new folder in the current folder</li>
 * <li><code>FileUpload</code>: Stores an uploaded file into the current
 * folder. (must be sent with POST)</li>
 * </ul>
 * 
 * @version $Id: ConnectorServlet.java 2101 2008-06-22 22:00:48Z mosipov $
 */
public class ConnectorServlet extends HttpServlet {

	private static final long serialVersionUID = -5742008970929377161L;
	private static final Logger logger = LoggerFactory.getLogger(ConnectorServlet.class);

	/**
	 * Initialize the servlet: <code>mkdir</code> &lt;DefaultUserFilesPath&gt;
	 */
	public void init() throws ServletException, IllegalArgumentException {
		String realDefaultUserFilesPath = getServletContext().getRealPath(
		        ConnectorHandler.getDefaultUserFilesPath());

		File defaultUserFilesDir = new File(realDefaultUserFilesPath);
		UtilsFile.checkDirAndCreate(defaultUserFilesDir);

		logger.info("ConnectorServlet successfully initialized!");
	}

	/**
	 * Manage the <code>GET</code> requests (<code>GetFolders</code>,
	 * <code>GetFoldersAndFiles</code>, <code>CreateFolder</code>).<br/>
	 * 
	 * The servlet accepts commands sent in the following format:<br/>
	 * <code>connector?Command=&lt;CommandName&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
	 * <p>
	 * It executes the commands and then returns the result to the client in XML
	 * format.
	 * </p>
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	        throws ServletException, IOException {
		logger.debug("Entering ConnectorServlet#doGet");

		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/xml; charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();

		String commandStr = request.getParameter("Command");
		String typeStr = request.getParameter("Type");
		String currentFolderStr = request.getParameter("CurrentFolder");

		logger.debug("Parameter Command: {}", commandStr);
		logger.debug("Parameter Type: {}", typeStr);
		logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

		XmlResponse xr;

		if (!RequestCycleHandler.isEnabledForFileBrowsing(request))
			xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.NOT_AUTHORIZED_FOR_BROWSING);
		else if (!CommandHandler.isValidForGet(commandStr))
			xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_COMMAND);
		else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
			xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_TYPE);
		else if (!UtilsFile.isValidPath(currentFolderStr))
			xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_CURRENT_FOLDER);
		else {
			CommandHandler command = CommandHandler.getCommand(commandStr);
			ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);

			String typePath = UtilsFile.constructServerSidePath(request, resourceType);
			String typeDirPath = getServletContext().getRealPath(typePath);

			File typeDir = new File(typeDirPath);
			UtilsFile.checkDirAndCreate(typeDir);

			File currentDir = new File(typeDir, currentFolderStr);

			if (!currentDir.exists())
				xr = new XmlResponse(XmlResponse.EN_INVALID_FOLDER_NAME);
			else {

				xr = new XmlResponse(command, resourceType, currentFolderStr, UtilsResponse
				        .constructResponseUrl(request, resourceType, currentFolderStr, true,
				                ConnectorHandler.isFullUrl()));

				if (command.equals(CommandHandler.GET_FOLDERS))
					xr.setFolders(currentDir);
				else if (command.equals(CommandHandler.GET_FOLDERS_AND_FILES))
					xr.setFoldersAndFiles(currentDir);
				else if (command.equals(CommandHandler.CREATE_FOLDER)) {
					
					//修改新建文件夹中文乱码
					
					 String temStr= request.getParameter("NewFolderName");
			        temStr=new String(temStr.getBytes("iso8859-1"),"utf-8");
					// 完毕
			        
					String newFolderStr = UtilsFile.sanitizeFolderName(temStr);
					logger.debug("Parameter NewFolderName: {}", newFolderStr);

					File newFolder = new File(currentDir, newFolderStr);
					int errorNumber = XmlResponse.EN_UKNOWN;

					if (newFolder.exists())
						errorNumber = XmlResponse.EN_ALREADY_EXISTS;
					else {
						try {
							errorNumber = (newFolder.mkdir()) ? XmlResponse.EN_OK
							        : XmlResponse.EN_INVALID_FOLDER_NAME;
						} catch (SecurityException e) {
							errorNumber = XmlResponse.EN_SECURITY_ERROR;
						}
					}
					xr.setError(errorNumber);
				}
			}
		}

		out.print(xr);
		out.flush();
		out.close();
		logger.debug("Exiting ConnectorServlet#doGet");
	}

	/**
	 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
	 * 
	 * The servlet accepts commands sent in the following format:<br />
	 * <code>connector?Command=&lt;FileUpload&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
	 * with the file in the <code>POST</code> body.<br />
	 * <br>
	 * It stores an uploaded file (renames a file if another exists with the
	 * same name) and then returns the JavaScript callback.
	 */
	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	        throws ServletException, IOException {
		logger.debug("Entering Connector#doPost");

		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();

		String commandStr = request.getParameter("Command");
		String typeStr = request.getParameter("Type");
		String currentFolderStr = request.getParameter("CurrentFolder");

		logger.debug("Parameter Command: {}", commandStr);
		logger.debug("Parameter Type: {}", typeStr);
		logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

		UploadResponse ur;

		// if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'
		// are empty
		if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) {
			commandStr = "QuickUpload";
			currentFolderStr = "/";
		}

		if (!RequestCycleHandler.isEnabledForFileUpload(request))
			ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null,
			        Messages.NOT_AUTHORIZED_FOR_UPLOAD);
		else if (!CommandHandler.isValidForPost(commandStr))
			ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
		else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
			ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
		else if (!UtilsFile.isValidPath(currentFolderStr))
			ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
		else {
			ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);

			String typePath = UtilsFile.constructServerSidePath(request, resourceType);
			String typeDirPath = getServletContext().getRealPath(typePath);

			File typeDir = new File(typeDirPath);
			UtilsFile.checkDirAndCreate(typeDir);

			File currentDir = new File(typeDir, currentFolderStr);

			if (!currentDir.exists())
				ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
			else {

				String newFilename = null;
				FileItemFactory factory = new DiskFileItemFactory();
				ServletFileUpload upload = new ServletFileUpload(factory);
			// 修改上传中文名乱码
				upload.setHeaderEncoding("UTF-8");
				//  完毕
				try {

					List<FileItem> items = upload.parseRequest(request);

					// We upload only one file at the same time
					FileItem uplFile = items.get(0);
					String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
					String filename = FilenameUtils.getName(rawName);
					String baseName = FilenameUtils.removeExtension(filename);
					String extension = FilenameUtils.getExtension(filename);
					
					//修改上传文件名字,用UUID方法
					filename=UUID.randomUUID().toString()+ "."+ extension;
					//  完毕
					
					
					
					
					
					
					//添加限制上传大小方法
					//如果这个文件的扩展名不允许上传
					
					if (!ExtensionsHandler.isAllowed(resourceType, extension))
						ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
					
					//如果超出大小10M
					else if(uplFile.getSize()> 10000 * 1024) 
					//传递一个自定义的错误码
						ur = new UploadResponse(204);
					
					// 如果不存在以上情况,则保存
					else {

						// construct an unique file name
						File pathToSave = new File(currentDir, filename);
						
						
						
						
						
						
						int counter = 1;
						while (pathToSave.exists()) {
							newFilename = baseName.concat("(").concat(String.valueOf(counter))
							        .concat(")").concat(".").concat(extension);
							pathToSave = new File(currentDir, newFilename);
							counter++;
						}

						if (Utils.isEmpty(newFilename))
							ur = new UploadResponse(UploadResponse.SC_OK, UtilsResponse
							        .constructResponseUrl(request, resourceType, currentFolderStr,
							                true, ConnectorHandler.isFullUrl()).concat(filename));
						else
							ur = new UploadResponse(UploadResponse.SC_RENAMED,
							        UtilsResponse.constructResponseUrl(request, resourceType,
							                currentFolderStr, true, ConnectorHandler.isFullUrl())
							                .concat(newFilename), newFilename);

						// secure image check
						if (resourceType.equals(ResourceTypeHandler.IMAGE)
						        && ConnectorHandler.isSecureImageUploads()) {
							if (UtilsFile.isImage(uplFile.getInputStream()))
								uplFile.write(pathToSave);
							else {
								uplFile.delete();
								ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
							}
						} else
							uplFile.write(pathToSave);

					}
				} catch (Exception e) {
					ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);
				}
			}

		}

		out.print(ur);
		out.flush();
		out.close();

		logger.debug("Exiting Connector#doPost");
	}

}



然后在WEB.XML 里修改为

Java代码 复制代码
  1. <servlet>   
  2.         <servlet-name>Connector</servlet-name>   
  3.         <servlet-class>   
  4.             com.fck.fckeditor.ConnectorServlet   
  5.         </servlet-class>   
  6.         <load-on-startup>1</load-on-startup>   
  7.     </servlet>   
  8.   
  9.     <servlet-mapping>   
  10.         <servlet-name>Connector</servlet-name>   
  11.         <!-- Do not wrap this line otherwise Glassfish will fail to load this file -->   
  12.         <url-pattern>/fckeditor/editor/filemanager/connectors/*</url-pattern>   
  13.     </servlet-mapping>  
<servlet>
		<servlet-name>Connector</servlet-name>
		<servlet-class>
			com.fck.fckeditor.ConnectorServlet
		</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>Connector</servlet-name>
		<!-- Do not wrap this line otherwise Glassfish will fail to load this file -->
		<url-pattern>/fckeditor/editor/filemanager/connectors/*</url-pattern>
	</servlet-mapping>



第四步是:限制上传文件类型,
根据 net.fckeditor.handlers  包下的default.properties 的配置
在我们新建的fckeditor.properties设置,用以覆盖defualt.properties里的设置

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值