`
guoxinzz
  • 浏览: 430857 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

FCKEditor用法

 
阅读更多

FCKeditor2.6.3系列(1)之下载即初步安装

在以前的文章中我曾经发布过一篇关于fckeditor2.6.3测试版本的使用即安装,地址:http://www.pjwqh.cn/css-131-jsp.html.感兴趣的朋友可以前去看看。现在正式版本已经发布有一段时间了,在这里我再写篇关于2.6.3正式版本的详细使用方法。

1.下载正式版本:(官方网站:http://www.fckeditor.net)
FCKeditor_2.6.3.zip:地址http://sourceforge.net/project/downloading.php?group_id=75348&filename=FCKeditor_2.6.3.zip
fckeditor-java-2.4-bin.zip (JAVA支持包)地址http://nchc.dl.sourceforge.net/sourceforge/fckeditor/fckeditor-java-2.4-bin.zip

2.解压以上两个压缩文件,分别从FCKeditor_2.6.3.zip中提取fckeditor文件夹,从fckeditor-java-2.4-bin.zip中提取fckeditor-java-core-2.4.jar
2.在MyEclipse中新建一个WEB项目,名叫FCKeditorTest,将提取到的fckeditor文件夹拷贝到项目WebRoot目录下,将提取到的fckeditor-java-core-2.4.jar拷贝到项目WebRoot/WEB-INF/lib目录下。

3.新建index.jsp页面,
第一种调用发方式(index.jsp):在

中加入<script type="text/javascript" src="fckeditor/fckeditor.js"></script>
在body中,在你需要显示编辑器的地方加入如下代码:
<script type="text/javascript"> <br /> var oFCKeditor = new FCKeditor( "FCKeditor1" ) ; <br /> oFCKeditor.BasePath="/FCKeditorTest/fckeditor/"; /*指定FCKeditor的基路径*/ <br /> oFCKeditor.Create() ; <br /> </script>

index.jsp代码:

String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>




<base href="&lt;%=basePath%&gt;">
My JSP 'index.jsp' starting page
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!-- <br /> <link rel="stylesheet" type="text/css" href="styles.css"> <br /> -->
<script type="text/javascript" src="fckeditor/fckeditor.js"></script>


<script type="text/javascript"> <br /> var oFCKeditor = new FCKeditor( "FCKeditor1" ) ; <br /> oFCKeditor.BasePath="/FCKeditor2.6.3/fckeditor/"; <br /> oFCKeditor.Create() ; <br /> </script>

第二中调用方式(index2.jsp):同样在在

中加入
<script type="text/javascript" src="fckeditor/fckeditor.js"></script>,
不同的是,还需要在head区域中加入
<script type="text/javascript"> <br /> window.onload=function(){ <br /> var oFCKeditor = new FCKeditor( "MyTestarea" ) ; <br /> oFCKeditor.BasePath="/FCKeditorTest/fckeditor/"; <br /> oFCKeditor.ReplaceTextarea(); <br /> } <br /> </script>
在body中,在你需要显示编辑器的地方写个textarea元素就可以了,但要注意,一定要给textarea元素的id或则name属性设置成 "MyTestarea",注意红色两处要一样。
index2.jsp代码:


String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>




<base href="&lt;%=basePath%&gt;">
My JSP 'index.jsp' starting page
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!-- <br /> <link rel="stylesheet" type="text/css" href="styles.css"> <br /> -->
<script type="text/javascript" src="fckeditor/fckeditor.js"></script>
<script type="text/javascript"> <br /> window.onload=function(){ <br /> var oFCKeditor = new FCKeditor( "MyTestarea" ) ; <br /> oFCKeditor.BasePath="fckeditor/"; <br /> oFCKeditor.ReplaceTextarea(); <br /> } <br /> </script>




====================================================================================================================

FCKeditor2.6.3系列(2)之JSP自定义标签调用

参考文档:http://java.fckeditor.net/java-core/tagreference.html

1.在上一节的基础上,在解压缩后的fckeditor-java-2.4-bin/fckeditor-java-2.4/lib目录下找到有三个jar文件,将他们一起拷贝到WebRoot/WEB-INF/lib/目录下,commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar是文件上传用的,slf4j-api-1.5.2.jar是记录日志用的.

2.新建index3.jsp,代码如下:

http://java.fckeditor.net" prefix="FCK" %>
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>




<base href="&lt;%=basePath%&gt;">
My JSP 'index.jsp' starting page
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!-- <br /> <link rel="stylesheet" type="text/css" href="styles.css"> <br /> -->


<editor instancename="MyEditor" basepath="/fckeditor/" value="this is contend"></editor>

运行,TOMCAT报错,提示找不到类java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder。为什么会提示找不到类呢,我们来看看官方网站的DEMO是什么样的。我们到官方网站上下载DEMO,http://sourceforge.net/project/showfiles.php?group_id=75348&package_id=129511,将这个WAR文件部署到TOMCAT里面让他自动解压,然后在解压文件中打开lib文件夹,发现里面有5个JAR包,我们自己的项目里面刚好少了其中一个JAR包slf4j-simple-1.5.2.jar,我们将其拷贝到项目WEB-INF/lib里面在来运行index3.jsp,OK,一切正常。
这里需要注意:

1.basePath属性必须一“/”开头,指定我们当前应用程序的当前路径。如basePath="/fckeditor/",这里跟上一节演示的有所不同,希望大家能注意。
2.FCK标签里的value属性必须给值,空格也行,否则程序会报NULLPOINTEXCEPTION异常。

==========================================================================================================================================================

FCKeditor2.6.3系列(3)之使用配置文件

参考文档:http://docs.fckeditor.net/FCKeditor_2.x/Developers_Guide/Configuration/Configuration_File

在fckeditor文件夹中找到fckconfig.js,这个文件就是FCKeditor的默认配置文件,我们可以修改其中的参数来实现对FCKeditor功能和样式皮

肤等的修改。例如,我们可以改变他的皮肤,找到FCKConfig.SkinPath = FCKConfig.BasePath + 'skins/default/' ;将其值改为

FCKConfig.SkinPath = FCKConfig.BasePath + 'skins/office2003/' ;这样就将其皮肤换成了office2003的皮肤了。FCKeditor提供了三中皮肤

,分别是default、office2003、silver。但这种修改配置文件是全局的,不管以后你在哪个页面调用编辑器,他们都共享同一个fckconfig.js

配置文件,如果我们想在文章评论中用一种样式或者限制FCKeditor的某种功能,但我们又得在网站后台发布文章的时候使用另外一种样式或者

启用某种功能的时候,修改fckconfig.js就办不到了。这时候我们有种解决办法:写两个额外的配置文件,在需要加上FCKeditor编辑器的地方

临时的指定使用哪个配置文件。

下面讲下使用额外的配置文件。
在WebRoot新建一个文件myconfig.js。内容写上FCKConfig.SkinPath = FCKConfig.BasePath + 'skins/silver/' ;这里我们将皮肤

设置成silver。我们要让我们自己的配置文件生效,有两种方法。一是修改fckconfig.js:找到FCKConfig.CustomConfigurationsPath = '' ;

将其改为FCKConfig.CustomConfigurationsPath = '/FCKeditorTest/myconfig.js' ;(/FCKeditorTest/myconfig.js为项目名称加配置文件名)

这种方法虽然能改变他的皮肤,但这里不能满足我们的需求,因为只要修改了fckconfig.js这个文件,就是全局的修改,就没有分不同情况使用

不同功能和样式编辑器可言了。那么只能用第二种方法了:在调用处指定使用哪个配置文件。例如我们用index.jsp调用为例,注意下面的代码

<script type="text/javascript"> <br /> var oFCKeditor = new FCKeditor( "FCKeditor1" ) ; <br /> oFCKeditor.BasePath="/FCKeditorTest/fckeditor/"; <br /> oFCKeditor.Config["CustomConfigurationsPath"] = "/FCKeditortest/myconfig.js" ; <br /> oFCKeditor.Create() ; <br /> </script>
运行,效果跟第一种方法一样,都将皮肤改成silver了,这样,我们就可以建立多个额外的配置文件,在调用处指定使用哪个配置文件就可以

实现在不同情况下使用不同配置的编辑器了。

这里需要提醒大家,不论你额外配置文件写的再好,fckconfig.js这个主配置文件是绝对不能删除的,不信,大伙可以试试哦

====================================================================================================================================

FCKeditor2.6.3系列(4)之自定义ToolBarSet

FCKeditor默认为我们提供了两种工具拦,分别是Default,Basic,我们查看fckconfig.js可以找到这样两处代码:
FCKConfig.ToolbarSets["Default"] = [
['Source','DocProps','-','Save','NewPage','Preview','-','Templates'],
['Cut','Copy','Paste','PasteText','PasteWord','-','Print','SpellCheck'],
['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
['Form','Checkbox','Radio','TextField','Textarea','Select','Button','ImageButton','HiddenField'],
'/',
['Bold','Italic','Underline','StrikeThrough','-','Subscript','Superscript'],
['OrderedList','UnorderedList','-','Outdent','Indent','Blockquote','CreateDiv'],
['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'],
['Link','Unlink','Anchor'],
['Image','Flash','Table','Rule','Smiley','SpecialChar','PageBreak'],
'/',
['Style','FontFormat','FontName','FontSize'],
['TextColor','BGColor'],
['FitWindow','ShowBlocks','-','About'] // No comma for the last row.
] ;

FCKConfig.ToolbarSets["Basic"] = [
['Bold','Italic','-','OrderedList','UnorderedList','-','Link','Unlink','-','About']
] ;

第一段代码就是Default的配置,第二段则为Basic的配置。''里面代表的是工具栏的各自功能按钮,-表示分隔符,/表示换一行,您可以对照着我们刚才配置的实例就可以知道每个''扩起来的短语代表什么功能了。
现在我们就来自定义一个我们自己的工具栏。
先将

FCKConfig.ToolbarSets["Default"] = [
['Source','DocProps','-','Save','NewPage','Preview','-','Templates'],
['Cut','Copy','Paste','PasteText','PasteWord','-','Print','SpellCheck'],
['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
['Form','Checkbox','Radio','TextField','Textarea','Select','Button','ImageButton','HiddenField'],
'/',
['Bold','Italic','Underline','StrikeThrough','-','Subscript','Superscript'],
['OrderedList','UnorderedList','-','Outdent','Indent','Blockquote','CreateDiv'],
['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'],
['Link','Unlink','Anchor'],
['Image','Flash','Table','Rule','Smiley','SpecialChar','PageBreak'],
'/',
['Style','FontFormat','FontName','FontSize'],
['TextColor','BGColor'],
['FitWindow','ShowBlocks','-','About'] // No comma for the last row.
] ;

拷贝到我们自己的额外配置文件myconfig.js中,然后将FCKConfig.ToolbarSets["Default"]修改一下,改成FCKConfig.ToolbarSets["myTool"];方便以后我们调用,然后根据你自己的需要删些短语,比如我们将第一个中括号以及里面的内容全部删除掉,这样我们自定义的工具栏就写好了,然后我们就只需在调用处指定使用myconfig.js这个配置文件,并且设置toolbarSet属性为"myTool"就可以了。我们用index3.jsp来示范一下:将代码

<editor instancename="MyEditor" basepath="/fckeditor/" value="this is contend"><br></editor>

修改为:

<editor instancename="MyEditor" basepath="/fckeditor/" toolbarset="myTool" value="this is contend"><br><br><config customconfigurationspath="/FCKeditorTest/myconfig.js"></config><br><br></editor>
然后我们访问这个页面,OK,我们的自定义的工具栏实现了。

注意:toolbarSet="myTool"是指定使用我们自定义的工具栏,默认为Deafault
CustomConfigurationsPath="/FCKeditorTest/myconfig.js"是指定使用我们自己写的额外配置文件
自己动手试试哦。

===========================================================================================================================================================

FCKeditor2.6.3系列(5)之常用字体添加

FCKeditor默认的字体都是些我不认识的,如果我想加上个“宋体”怎么办呢,其实很简单,只需要在fckconfig.js中找到如下代码

FCKConfig.FontNames= 'Arial;Comic Sans MS;Courier New;Tahoma;Times New Roman;Verdana' ;

将其修改为:

FCKConfig.FontNames= '宋体;楷体_GB2312;黑体;隶书;

现在再来运行index3.jsp看看效果,OK,我们现在可以成功的见到我们熟悉的字体了。

这种修改是全局的,当然你也可以在额外配置文件中设置。

=============================================================================================================================

FCKeditor2.6.3系列(6)之自定义表情

FCKeditor默认给我们提供的图片,说实话,个人感觉真是丑的个无法形容。幸好,我们还可以修改这些丑的无法形容的表情,下面大家就跟着我做吧。

首先我们要下载我们喜欢的表情图片,我也懒的上网找,QQ的表情已经很丰富可爱了,我就用它来举例吧。我们到QQ安装目录下face文件夹中挑选出我们喜欢的表情图片,然后在项目的fckeditor/editor/images/smiley文件夹中新建一个文件夹,名为myface,将我们的QQ表情复制到myface文件夹中待用。

然后在fckconfig.js中找到下面代码:
FCKConfig.SmileyPath = FCKConfig.BasePath + 'images/smiley/msn/' ;/*表情图片路径,默认为msn文件夹,我们可以修改*/
FCKConfig.SmileyImages = ['regular_smile.gif','sad_smile.gif','wink_smile.gif','teeth_smile.gif','confused_smile.gif','tounge_smile.gif','embaressed_smile.gif','omg_smile.gif','whatchutalkingabout_smile.gif','angry_smile.gif','angel_smile.gif','shades_smile.gif','devil_smile.gif','cry_smile.gif','lightbulb.gif','thumbs_down.gif','thumbs_up.gif','heart.gif','broken_heart.gif','kiss.gif','envelope.gif'] ;/*‘’中的名字对应表情图片文件夹中的图片名称,我们可以修改*/
FCKConfig.SmileyColumns = 8 ;/*每行显示的图片数量,我们可以修改*/
FCKConfig.SmileyWindowWidth = 320 ;/*表情窗口宽度,我们可以修改*/
FCKConfig.SmileyWindowHeight = 210 ;/*表情窗口高度,我们可以修改*/

每句配置的意思我已经注明了,聪明的你现在应该知道该怎么做了吧,^_^。对了,首先得吧表情图片路径给改了,这里将msn改成myface;下面修改每张图片的名字,比如我们myface文件夹下有张0.gif的图片,我们就需要这样修改:FCKConfig.SmileyImages =['0.gif'],这里工作量有点大了哦,慢慢来吧。修改完了我们来试试。OK,如果你照这我做的话效果因该出来了,恭喜……

这里有一点需要提出,QQ表情图片的大小比叫小(长和宽),如果换成比较大的图片,或者你的图片比较多的话你的编辑器表情弹出窗口就会跟着增大,导致整个屏幕无法全部显示,我们来给编辑器表情弹出窗口增加一个功能——显示下拉条。
在fckeditor/editor/dialog目录下找到fck_smiley.html修改他的代码,找到:
window.onload = function ()
{
// First of all, translate the dialog box texts
oEditor.FCKLanguageManager.TranslatePage(document) ;

dialog.SetAutoSize( true ) ;
}

1.将第一段代码的dialog.SetAutoSize( true ) 删除掉,
2.将overflow:hidden改为overflow:scroll
Ok,现在我们的修改已经完全做好了,刷新一下页面,在点击表情,就可以看到弹出的窗口有下拉条了。

===========================================================================================================================================

FCKeditor2.6.3系列(7)之文件上传基本配置

到目前为止我们还不能实现文件上传,比如上传图片,flash等,实现文件上传也很简单,参考文档:

http://java.fckeditor.net/connector.html

分两不进行:

1.首先复制下面代码:

<servlet><br><servlet-name>Connector</servlet-name><br><servlet-class><br> net.fckeditor.connector.ConnectorServlet <br></servlet-class><br><load-on-startup>1</load-on-startup><br></servlet>
<servlet-mapping><br><servlet-name>Connector</servlet-name><br><url-pattern><br> /fckeditor/editor/filemanager/connectors/* <br></url-pattern><br></servlet-mapping>

将其复制到项目web.xml里面

2.在src目录下新建fckeditor.properties文件,注意文件名不能错误,内容为:
connector.userActionImpl=net.fckeditor.requestcycle.impl.UserActionImpl

到目前为止我们的文件上传功能配置好了。

==================================================================================================================================

FCKeditor2.6.3系列(8)之上传中文名文件时文件名乱码

在本系列文章之前的一篇文章里曾经讲过关于乱码的解决办法,但过于复杂而且不稳定,现在给大家一个简单易行的处理方法。

1.首先在下载的FCKEeditor java源代码fckeditor-java-2.4-src/fckeditor-java-2.4/java-core/src/main/java/net/fckeditor/connector这个路径下找到ConnectorServlet.java,将其中的源代码全部复制待用。
2.在src目录下建立如下的一个类文件:ConnectorServlet.java(包名自己设置,我设置的为com.pjwqh.fckeditor)
将刚才复制的内容粘贴过来,注意红色的为我添加的代码
package com.pjwqh.fckeditor;

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

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.

*
* This servlet accepts 4 commands which interact with the server-side
* filesystem.

* The allowed commands are:
*


    *
  • GetFolders: Retrieves a list of folders in the current
    * folder

  • *
  • GetFoldersAndFiles: Retrives a list of files and folders
    * in the current folder

  • *
  • CreateFolder: Creates a new folder in the current folder

  • *
  • FileUpload: Stores an uploaded file into the current
    * folder. (must be sent with POST)

  • *

*
* @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: mkdir <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 GET requests (GetFolders,
* GetFoldersAndFiles, CreateFolder).

*
* The servlet accepts commands sent in the following format:

* connector?Command=<CommandName>&Type=<ResourceType>&CurrentFolder=<FolderPath>
*


* It executes the commands and then returns the result to the client in XML
* format.
*


*/
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 newFolderStr = UtilsFile.sanitizeFolderName(request
.getParameter("NewFolderName"));
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 POST requests (FileUpload).

*
* The servlet accepts commands sent in the following format:

* connector?Command=<FileUpload>&Type=<ResourceType>&CurrentFolder=<FolderPath>
* with the file in the POST body.

*

* 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);

try {
upload.setHeaderEncoding("UTF-8");
List<fileitem> items = upload.parseRequest(request);</fileitem>

// 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);

if (!ExtensionsHandler.isAllowed(resourceType, extension))
ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
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");
}

}

3.修改web.xml文件
注意我修改后的web.xml文件,红色的为我修改的地方:
<servlet><br><servlet-name>Connector</servlet-name><br><servlet-class><br> com.pjwqh.fckeditor.ConnectorServlet <br></servlet-class><br><load-on-startup>1</load-on-startup><br></servlet>
<servlet-mapping><br><servlet-name>Connector</servlet-name><br><url-pattern><br> /fckeditor/editor/filemanager/connectors/* <br></url-pattern><br></servlet-mapping>

好了,到目前为止,中文名文件的上传修改成了。

=======================================================================================================================================================

FCKeditor2.6.3系列(9)之创建中文名文件夹时文件名乱码

FCKeditor创建中文名文件夹时中文文件名乱码了,我们可以经过如下修改解决这个问题。

方法一:我们还得修改ConnectorServlet.java,注意红色的为我的修改代码:

package com.pjwqh.fckeditor;

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

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.

*
* This servlet accepts 4 commands which interact with the server-side
* filesystem.

* The allowed commands are:
*


    *
  • GetFolders: Retrieves a list of folders in the current
    * folder

  • *
  • GetFoldersAndFiles: Retrives a list of files and folders
    * in the current folder

  • *
  • CreateFolder: Creates a new folder in the current folder

  • *
  • FileUpload: Stores an uploaded file into the current
    * folder. (must be sent with POST)

  • *

*
* @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: mkdir <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 GET requests (GetFolders,
* GetFoldersAndFiles, CreateFolder).

*
* The servlet accepts commands sent in the following format:

* connector?Command=<CommandName>&Type=<ResourceType>&CurrentFolder=<FolderPath>
*


* It executes the commands and then returns the result to the client in XML
* format.
*


*/
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 tempName=new String(request.getParameter("NewFolderName").getBytes("ISO8859-1"),"UTF-8");
String newFolderStr = UtilsFile.sanitizeFolderName(tempName);
/*String newFolderStr = UtilsFile.sanitizeFolderName(request
.getParameter("NewFolderName"));*/
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 POST requests (FileUpload).

*
* The servlet accepts commands sent in the following format:

* connector?Command=<FileUpload>&Type=<ResourceType>&CurrentFolder=<FolderPath>
* with the file in the POST body.

*

* 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);

try {
upload.setHeaderEncoding("UTF-8");
List<fileitem> items = upload.parseRequest(request);</fileitem>

// 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);

if (!ExtensionsHandler.isAllowed(resourceType, extension))
ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
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");
}

}
方法二:
修改TOMCAT配置文件:
找到:
<connector port="8080" protocol="HTTP/1.1"></connector> maxThreads="150" connectionTimeout="20000"
redirectPort="8443"/>
增加一个属性:
URIEncoding="UTF-8"
修改之后为:
<connector port="8088" protocol="HTTP/1.1"></connector> maxThreads="150" connectionTimeout="20000"
redirectPort="8443"
URIEncoding="UTF-8"/>
注意,这两个方法不能同时使用。
呵呵,简单吧。

===============================================================================================================================================================================

FCKeditor2.6.3系列(10)之引用中文名图片时不能正常显示

这里有两个方法解决引用中文图片不能正常显示的问题。

方法一:
修改TOMCAT配置文件:
找到:
<connector port="8080" protocol="HTTP/1.1"></connector> maxThreads="150" connectionTimeout="20000"
redirectPort="8443"/>
增加一个属性:
URIEncoding="UTF-8"
修改之后为:
<connector port="8088" protocol="HTTP/1.1"></connector> maxThreads="150" connectionTimeout="20000"
redirectPort="8443"
URIEncoding="UTF-8"/>
方法二:修改ConnectorServlet.java,我们是思路是给上传的文件重命名,让他不含中文字符,这里使用UUID方法:
找到如下代码:
String filename = FilenameUtils.getName(rawName);
String baseName = FilenameUtils.removeExtension(filename);
String extension = FilenameUtils.getExtension(filename);
在其后添加如下代码:
filename=UUID.randomUUID().toString()+"."+extension;

OK,现在来运行下我们的程序,可以看到上传的中文名文件被重命名成了一个很长的字符串,这样就避免了出现中文乱码的烦恼。

===========================================================================================================================================================

FCKeditor2.6.3系列(11)之允许上传的文件类型

如果我们在上传图片的时候你想上传一个exe文件是不能成功的,但我们可以通过修改配置文件来允许我们上传各种各样的文件和拒绝上传某类文件。
开始之前我们要明白两个概念:客户端配置文件和服务器端配置文件。
在本系列的第一节我们曾经新建过一个文件fckeditor.properties,这个就是服务器端的配置文件;
我们自己建立的myconfig.js和默认的fckconfig.js就是客户端配置文件。
这里我们需要修改这两处的配置,确保客户端和服务器端的配置相同。
其实FCKeditor自己有个default.properties文件,位置在net.fckeditor.handlers包下。我们就是根据覆盖这个文件里的部分属性来实现我们上传exe文件的功能。

修改服务器端配置文件:

找到connector.resourceType.image.extensions.allowed = bmp|gif|jpeg|jpg|png
复制到fckeditor.properties中,
修改为:connector.resourceType.image.extensions.allowed = bmp|gif|jpeg|jpg|png|exe

修改客户端配置文件:

在fckconfig.js中找到
FCKConfig.ImageUploadAllowedExtensions = ".(jpg|gif|jpeg|png|bmp)$" ; // empty for all
复制到myconfig.js中
修改为FCKConfig.ImageUploadAllowedExtensions = ".(jpg|gif|jpeg|png|bmp|exe)$" ; // empty for all

好了,先在你可以在上传图片的时候上传exe文件了。
同理你可以根据你自己的需要修改配置来满足你自己的上传功能。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics