1.下载FCKeditor *.*.*
2.下载fckeditor-java-*.*.*-bin.zip
3.下载fckeditor-java-demo-*.*.*.war (可作为参考)
demo的查看、doc文档的查看
下载的说明,涉及java还得下个包 war工程的查看
安装与通过JavaScript调用FCKeditor的两种方法
部署:拷贝到webroot下
fckeditor的调用方式:
1.通过javascript调用
2.在jsp中通过自定义标签调用
参考方式: 附带的例子 samples里 文档
通过javascript调用
方法一:
<script type="text/javascript" src="fckeditor/fckeditor.js"></script> <script type="text/javascript"><!-- 编辑器创建 --> var oFCKeditor = new FCKeditor("FCKeditor1"); oFCKeditor.BasePath = "/test/fckeditor/";<!-- fckedior绝对路径,/结尾 --> oFCKeditor.Create(); </script>
方法二:
<script type="text/javascript" src="fckeditor/fckeditor.js"></script>
<head></head>里添加
<script type="text/javascript">
window.onload=function(){
var oFCKeditor = new FCKeditor("MyTextarea");<!-- 下面指定 -->
oFCKeditor.BasePath = "fckeditor/";<!-- fckedior相对路径,/结尾 -->
oFCKeditor.ReplaceTextarea();
}
< /script>
<body></body>里添加
<textarea id="MyTextarea" name="MyTextarea">this is</textarea>
方法三:
注意:BasePath要正确的设置 BasePath一定要以“/”结尾
fckeditor对象属性
Width 默认100%
Height 默认200
ToolbarSet 默认default
BasePath 默认/fckeditor/
构造器
var FCKeditor = function(instanceName,width,height,toolbarSet,value)
instanceName为编辑器输出的textarea元素的name属性值,必须指定
参数会赋值给同名属性
在jsp中通过自定义标签调用FCKeditor
参考 演示工程 帮助文档 jar文件拷贝
步骤: 拷贝jar文件
<%@ taglib uri="http://java.fckeditor.net" prefix="FCK" %>
<FCK:editor instanceName="myEditor" basePath="/fckeditor" value="haha"></FCK:editor>
注意:basePath要以“/”开头,/代表当前工程路径 一定要设置value属性的值,并且值不能为空字符串
配置_使用配置文件
webroot下创建myconfig.js文件
FCKConfig.AutoDetectLanguage=false; 自动检测语言
FCKConfig.DefaultLanguage="fr";
在默认的配置文件里
一、FCKConfig.CustomConfigurationsPath='/test/myconfig.js';
二、在创建编辑器时指定下 oFCKeditor.Config["CustomConfigurationsPath"]="/test/myconfig.js"; 只对当前有效
配置FCKeditor三种方式
直接修改主配置文件 fckconfig.js
定义单独的配置文件(只需用写需要修改的配置项)
在页面的调用代码中对FCKeditor的实例进行配置
配置加载顺序
1.加载主配置文件fckconfig.js
2.加载自定义的配置文件(如果有),覆盖相同的配置项
3.使用对实例的配置覆盖相同的配置项(只对当前实例有效)
提示
系统会自动侦测并运用适当的界面语言(默认,可以修改)
不能删除主配置文件fckconfig.js
修改配置后要清空浏览器缓存,以免影响结果 (或访问时强制刷新也可以) IE:Ctrl+F5 Firefox:Shift+Ctrl+R
配置_一般需要修改的配置
一般需要修改的配置
自定义ToolbarSet,去掉一些功能
加上几种常用的字体
修改"回车"和"Shift+回车"的换行行为
修改编辑区的样式
更换表情图片
自定义ToolbarSet,去掉一些功能
先自定义工具集再引用该工具集
关于自定义工具集选择的工具看 '-'代表分隔符'|' '/'代表换行符
加上几种常用的字体
FCKConfig.FontNames = '实体;楷体_GB2312;黑体;隶书;Times New Roman;Arial';
修改"回车"和"Shift+回车"的换行行为
FCKConfig.EnterMode = 'br'; // p | div | br
FCKConfig.ShiftEnterMode = 'p';
修改编辑区的样式
文件路径 FCKConfig.basePath下 alert()下就知道在哪了
配置_更换表情图片
配置选项
FCKConfig.SmileyPath = ''; //文件路径
FCKConfig.SmileyImages = ['','']; //路径下的图片名称
FCKConfig.SmileyColumns = 8; //每行显示数量
FCKConfig.SmileyWindowWidth = 320; //窗体宽度
FCKConfig.SmileyWindowHeight =210; //窗体高度
单个添加更换或整个文件夹更换 想添加滚动条,查看窗体的文件进行修改
FCKConfig.CustomConfigurationsPath='/test/myconfig.js';
工程不确定,应该修改为 FCKConfig.CustomConfigurationsPath=FCKConfig.EditorPath+'myconfig.js';
注意: 自定义的配置文件要使用UTF-8编码保存
FCKConfig.BasePath和调用fckeditor时指定的 BasePath(FCKeditor.BasePath)不是同一个,其值也不一样
文件上传_基本使用
使用看java关联的文档
步骤 在web.xml文件添加一个servlet
<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>
在classpath下新建fckeditor.properties //名字路径不能改变
里面内容
connector.userActionImpl=net.fckeditor.requestcycle.impl.UserActionImpl
文件上传_问题一_上传中文名的文件会出现乱码
使用文件上传会遇到下面问题
上传中文名的文件会出现乱码
创建中文名的目录时会出现乱码
引用的中文名字的图片不能正常显示 解决:写个servlet把post方法中setHeaderEncoding("utf-8");
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> <DefaultUserFilesPath>
*/
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=<CommandName>&Type=<ResourceType>&CurrentFolder=<FolderPath></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=<FileUpload>&Type=<ResourceType>&CurrentFolder=<FolderPath></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");
}
}
问题二_创建中文名的目录时会出现乱码
解决:在servlet的get方法,当request.getParameter("");之后重新编码
问题三_引用的中文名字的图片不能正常显示
解决:
方案一:修改tomcat的servlet.xml在<Connector>添加URIEncoding="UTF-8" 不推荐使用,因为将对创建中文文件夹有影响
方案二:避免使用中文名称保存图片,在servlet修改,采用UUID随机设置名称
文件上传允许上传的文件类型
a.控制允许上传的文件类型
FCKeditor把文件的上传分成4类
File
Image
Flash
Media
b.设置允许上传的文件扩展名列表 禁止上传的文件扩展名列表 只能配置一项
c.修改时除了media客户端不用设置,其它的客户端和服务器端都必须设置,且设置相同
文件上传允许上传的文件的大小
步骤: 在服务器端的servlet中,在保存文件之前先判断一下文件的大小,
如果超出限制,就传递一个自定义的错误码,并且不再保存文件 修改对应界面的回调函数,增加对这个自定义的错误码的处理
在表单中使用FCKeditor a.一般都放在表单中提交,只要放在<form></form>中 b.通过fckeditor提交的中文内容,在服务器端得到的为乱码的解决