`
coolworm
  • 浏览: 44466 次
  • 性别: Icon_minigender_1
  • 来自: 北京
最近访客 更多访客>>
社区版块
存档分类
最新评论

FCKeditor的详细配置

阅读更多
  研究了几天的FCKeditor,终于对他的详细配置有了一个详细的了解,现写成文章,希望对大家的学习有帮助(版本是FCKeditor 2.6.3)
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 输入
<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 :
输入
connector.userActionImpl=net.fckeditor.requestcycle.impl.UserActionImpl


第三步是解决上传中文乱码的问题
我们新建一个类 比如 com.fck.fckeditor.ConnectorServlet
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 里修改为
<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里的设置

备注:

以上是配置的大致方法,比较麻烦的是 配置限制上传文件大小,在这说不清楚,想学习的朋友,可下载我的配置作为参考~!  谢谢大家

  • fck.rar (2.8 MB)
  • 下载次数: 3607
分享到:
评论
7 楼 tuoxinquyu 2012-02-23  
为什么我的还是不管用呢,过滤器也配了,但是上传的时候图片还是被编码了
比如/test_study/userfiles/image/%E9%9B%AA%E4%BA%BA_2(2).jpg,这样图片根本没法显示,有什么好的解决办法呢?
6 楼 蝴铁花 2009-01-23  
学习一下。。。。。
5 楼 china_vip_java 2008-12-22  
coolworm 写道
(版本是FCKeditor 2.6.3)
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 输入
<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 :
输入
connector.userActionImpl=net.fckeditor.requestcycle.impl.UserActionImpl


第三步是解决上传中文乱码的问题
我们新建一个类 比如 com.fck.fckeditor.ConnectorServlet
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 里修改为
<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里的设置

4 楼 eason007 2008-12-19  
fck的文件上传一直有问题,都几年了。

以前asp的时候很容易被搞死,居然上传文件不改名。。。。
3 楼 lonelydark 2008-12-05  
哈哈..我今天也要研究这个东东.....不过上官网的速度太慢了.
2 楼 fengsky491 2008-11-22  
学习学习。。。
1 楼 walkman 2008-11-14  
我觉得 fckeditor 最大的隐患在权限控制上,上传文件首当其冲,希望楼主多多研究一下这方面啊,呵呵

相关推荐

    FckEditor中文配置手册详细说明

    FCKEditor 中文配置手册详细说明 FCKEditor 是一个功能强大且广泛使用的富文本编辑器,它提供了多种功能,如格式化文本、插入图片、插入链接、表格操作等。下面是 FCKEditor 中文配置手册详细说明。 一、下载和...

    fckeditor的配置详解

    **fckeditor的配置详解** **一、fckeditor基础配置** FCKeditor是一款开源的富文本编辑器,广泛应用于网页编辑器开发,它提供了丰富的文本格式化功能,如字体、字号、颜色、对齐方式等。在使用FCKeditor时,对其...

    FCKeditor2.5配置教程

    本教程将详细介绍如何配置FCKeditor 2.5。 ### 一、下载与解压 首先,你需要从官方或第三方源下载FCKeditor 2.5的压缩包文件。下载完成后,解压缩到你的本地文件系统中,通常你会得到一个名为`FCKeditor`的目录,...

    FCKeditor配置for java

    **FCKeditor配置for Java** FCKeditor是一款流行的开源富文本编辑器,广泛应用于Web开发中,为用户提供类似于Microsoft Word的界面,使用户能够轻松创建和编辑HTML内容。在Java Web开发环境中,集成FCKeditor可以...

    基于jsp的FCKeditor终于配置好了

    【标题】基于jsp的FCKeditor配置详解 在Web开发中,富文本编辑器(Rich Text Editor)常常用于提供用户友好的内容输入界面,FCKeditor便是其中一款经典的开源编辑器。本文将深入探讨如何在Java Web环境中,利用JSP...

    Fckeditor 2.6.3 配置(ASP.NET)

    本文将详细介绍如何在ASP.NET环境中配置并使用Fckeditor 2.6.3版本。 #### 二、下载与安装 1. **下载Fckeditor**: - 访问官方网站:[http://www.fckeditor.net/download](http://www.fckeditor.net/download) -...

    ASP.NET下FCKeditor配置方法全解

    总的来说,ASP.NET中的FCKeditor配置涉及前端JavaScript的实例化,后端代码的处理,以及可能的自定义配置和安全措施。通过合理的配置和使用,FCKeditor可以极大地提升用户在Web应用程序中的编辑体验。

    FCKeditor配置方法

    接下来是FCKeditor的详细配置,主要通过编辑fckconfig.js文件完成: 1. 修改文件浏览器和快速上传的语言设置,将`_FileBrowserLanguage`和`_QuickUploadLanguage`的值更改为与你的开发环境匹配,例如,对于ASP.NET...

    fckeditor的JSP详细配置(带有所有需要的包)

    这个是自己调试并整理过的fckeditor配置,并非网上照搬照抄的垃圾文档。包含有所有需要的包,配置说明,servlet文件 注: 1、要想实现上传必须用自定义标签方式引用。 2、SSH结合时上传功能失败,删除xalan.jar...

    已经配置好的Fckeditor

    Fckeditor的配置过程包括了几个关键步骤: 1. **安装和下载**:首先,需要从Fckeditor的官方网站获取最新版本的编辑器包,这个包通常包含了所有必要的文件和资源。 2. **环境准备**:确保你的开发环境已经配置好了...

    FckEditor中文配置手册详细说明.doc

    FckEditor中文配置手册详细说明.doc

    FckEditor 中文配置手册

    FckEditor 中文配置手册,对于fckeditor不是很熟悉的朋友可以看下。快速的掌握这个应用比较广泛的网页在线编辑器。

    java /jsp FCKeditor 配置

    通过复制粘贴实现FCKeditor 的使用. 看拉大家的留言,为使大家下载多能使用,补充个注意点; 在jsp页面出现FCKeditor 引用错误. 把页面中的下面代码中 id="infoContent" basePath="../../FCKeditor/" width="822" ...

    fckeditor2.4.1配置

    **FCKeditor 2.4.1 配置详解** FCKeditor 是一款开源的、基于 JavaScript 的富文本编辑器,广泛应用于Web开发中,允许用户在网页上进行类似Word的文本编辑操作。版本2.4.1是其较早的一个稳定版本,尽管现在有更新的...

    FckEditor 中文配置手册详细说明

    ### FckEditor中文配置手册详细说明 #### 一、引言 FckEditor是一款非常流行的富文本编辑器,因其良好的性能、丰富的功能以及简洁的界面设计,在众多在线编辑器中脱颖而出。本文旨在深入探讨FckEditor的核心优势...

    FCKeditor简单配置使用

    总结,"FCKeditor简单配置使用"主要涵盖了如何在JSP页面中快速集成和使用FCKeditor的基本步骤。虽然在这个示例中没有涉及到数据库交互,但在实际应用中,我们通常会将FCKeditor编辑的内容保存到数据库中,以便后续的...

    FckEditor中文配置手册详细说明.docx

    《FckEditor中文配置手册详细说明》 FckEditor是一款优秀的在线文本编辑器,以其出色的性能和易用性受到广大用户的青睐。相比其他编辑器,如CUTEEDITOR和FREETEXTBOX,FckEditor在加载速度和功能集成上具有明显优势...

Global site tag (gtag.js) - Google Analytics