最近写个blog 用java用到了富文本编辑器,本来是用xheditor但是发现上传图片实在是麻烦。还是改用fckeditor。
直接来步骤:
1、下载地址https://sourceforge.net/projects/fckeditor/files/FCKeditor.Java/2.6/
直接下载这两个fckeditor-java-demo-2.6.war ,fckeditor-java-2.6-src.zip 不用说 第一个是例子 第二个是源码。
2、解压.war 这个包把里面的lib下的jar文件copy到自己项目lib下。war包中有个fckeditor.properties文件拷贝到自己工程下的src中。最好不要修改这个文件,我修改了文件指定上传图片的路径后就没办法上传了。所以copy过去就行不用管。
3、打开自己的web.xml 添加
<!-- fck begin --> <servlet> <servlet-name>ConnectorServlet</servlet-name> <servlet-class> net.fckeditor.connector.ConnectorServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>ConnectorServlet</servlet-name> <url-pattern>/fckeditor/editor/filemanager/connectors/*</url-pattern> </servlet-mapping> <!-- fck end -->
如果用struts2了要这样写filter
<filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>*.action</url-pattern> <url-pattern>*.jsp</url-pattern> </filter-mapping>
不能直接/*,说是和struts2冲突,自己没试过。
4、将war包中的fckeditor文件夹整个copy到webroot下不用动。
5、新建jsp页面内容如下
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.fckeditor.net" prefix="FCK" %>
<html>
<head>
<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">
</head>
<body>
<form action="">
<FCK:editor instanceName="EditorDefault" toolbarSet="Default" width="750" height="550">
<jsp:attribute name="value">This is some <strong>sample text
</strong>. You are using <a href="http://www.fckeditor.net">
FCKeditor</a>.
</jsp:attribute>
</FCK:editor>
<input type="submit" value="提交"/>
</form>
</body>
</html>
6、直接访问该jsp试试能不能上传图片,按步骤来就没问题。至此完成。
其他说明:fckeditor文件夹中有一个fckconfig.js文件时用来配置fck属性的,从网上找了一段配置信息
/*
* 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 ==
*
* Editor configuration settings.
*
* Follow this link for more information:
* http://wiki.fckeditor.net/Developer%27s_Guide/Configuration/Configurations_Settings
*/
FCKConfig.CustomConfigurationsPath = '' ;//自定义配置文件路径和名称
FCKConfig.EditorAreaCSS = FCKConfig.BasePath + 'css/fck_editorarea.css' ;// 编辑区的样式表文件
FCKConfig.EditorAreaStyles = '' ;// 编辑区的样式表风格
FCKConfig.ToolbarComboPreviewCSS = '' ; //工具栏预览CSS
FCKConfig.DocType = '' ;//文档类型
FCKConfig.BaseHref = '' ;// 相对链接的基地址
FCKConfig.FullPage = false ;//是否允许编辑整个HTML文件,还是仅允许编辑BODY间的内容
// The following option determines whether the "Show Blocks" feature is enabled or not at startup.
FCKConfig.StartupShowBlocks = false ;//决定是否启用"显示模块"
FCKConfig.Debug = false ;//是否开启调试功能,当调用FCKDebug.Output()时,会在调试窗中输出内容
FCKConfig.AllowQueryStringDebug = true ;
FCKConfig.SkinPath = FCKConfig.BasePath + 'skins/office2003/' ;//皮肤路径换成这个皮肤感觉更好看
FCKConfig.SkinEditorCSS = '' ; // FCKConfig.SkinPath + "|<minified css>" ;
FCKConfig.SkinDialogCSS = '' ; // FCKConfig.SkinPath + "|<minified css>" ;
FCKConfig.PreloadImages = [ FCKConfig.SkinPath + 'images/toolbar.start.gif', FCKConfig.SkinPath + 'images/toolbar.buttonarrow.gif' ] ;//预装入的图片
FCKConfig.PluginsPath = FCKConfig.BasePath + 'plugins/' ;//插件路径
// FCKConfig.Plugins.Add( 'autogrow' ) ;
// FCKConfig.Plugins.Add( 'dragresizetable' );
FCKConfig.AutoGrowMax = 400 ;
// FCKConfig.ProtectedSource.Add( /<%[\s\S]*?%>/g ) ; // ASP style server side code <%...%>
// FCKConfig.ProtectedSource.Add( /<\?[\s\S]*?\?>/g ) ; // PHP style server side code
// FCKConfig.ProtectedSource.Add( /(<asp:[^\>]+>[\s|\S]*?<\/asp:[^\>]+>)|(<asp:[^\>]+\/>)/gi ) ; // ASP.Net style tags <asp:control>
FCKConfig.AutoDetectLanguage = true ; //是否自动检测语言
FCKConfig.DefaultLanguage = 'zh-cn' ;//默认语言
FCKConfig.ContentLangDirection = 'ltr' ;//默认的文字方向,可选"ltr/rtl",即从左到右或从右到左
FCKConfig.ProcessHTMLEntities = true ;//处理HTML实体
FCKConfig.IncludeLatinEntities = true ;//包括拉丁文
FCKConfig.IncludeGreekEntities = true ;//包括希腊文
FCKConfig.ProcessNumericEntities = false ;//处理数字实体
FCKConfig.AdditionalNumericEntities = '' ; // Single Quote: "'"
FCKConfig.FillEmptyBlocks = true ;//是否填充空块,使用这个功能,可以将空的块级元素用空格来替代
FCKConfig.FormatSource = true ;//在切换到代码视图时是否自动格式化代码
FCKConfig.FormatOutput = true ;//当输出内容时是否自动格式化代码
FCKConfig.FormatIndentator = ' ' ;//当在"源码格式"下缩进代码使用的字符
//FCKConfig.GeckoUseSPAN = true/false; // 是否允许SPAN标记代替B,I,U标记
FCKConfig.StartupFocus = false ;//开启时焦点是否到编辑器,即打开页面时光标是否停留在fckeditor上
FCKConfig.ForcePasteAsPlainText = false ;//是否强制粘贴为纯文件内容
FCKConfig.AutoDetectPasteFromWord = true ; //是否自动探测从word粘贴文件,仅支持IE IE only.
FCKConfig.ShowDropDialog = true ;//是否显示下拉菜单
FCKConfig.ForceSimpleAmpersand = false ;//是否不把&符号转换为XML实体
FCKConfig.TabSpaces = 1 ;//在编辑器区域内可以使用TAB键,按下Tab键时光标跳格数,默认值为0为不跳格,1为有效,4为产生的空格字符数
FCKConfig.ShowBorders = true ;//合并边框
FCKConfig.SourcePopup = false ;//弹出
FCKConfig.ToolbarStartExpanded = false ; //启动fckeditor工具栏默认是否展开
FCKConfig.ToolbarCanCollapse = true ; //是否允许折叠或展开工具栏
FCKConfig.IgnoreEmptyParagraphValue = true ; //是否忽略空的段落值
FCKConfig.PreserveSessionOnFileBrowser = false ;
FCKConfig.FloatingPanelsZIndex = 10000 ; //浮动面板索引
FCKConfig.HtmlEncodeOutput = false ; //是否将HTML编码输出
FCKConfig.TemplateReplaceAll = true ; //是否替换所有模板
FCKConfig.TemplateReplaceCheckbox = true ;
FCKConfig.ToolbarLocation = 'In' ; //工具栏位置
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'],
['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']
] ;
FCKConfig.ToolbarSets["myBasic"] = [
['Bold','Italic','Unlink','-','Style','FontSize','TextColor','BGColor','-','Smiley','SpecialChar','Replace','Preview']
] ;
FCKConfig.EnterMode = 'p' ; //编辑器中直接回车,在代码中生成,可选为 p | div | br
FCKConfig.ShiftEnterMode = 'br' ; //编辑器中Shift+回车,在代码中生成,可选为 p | div | br
FCKConfig.Keystrokes = [
[ CTRL + 65 /*A*/, true ],
[ CTRL + 67 /*C*/, true ],
[ CTRL + 70 /*F*/, true ],
[ CTRL + 83 /*S*/, true ],
[ CTRL + 84 /*T*/, true ],
[ CTRL + 88 /*X*/, true ],
[ CTRL + 86 /*V*/, 'Paste' ],
[ SHIFT + 45 /*INS*/, 'Paste' ],
[ CTRL + 88 /*X*/, 'Cut' ],
[ SHIFT + 46 /*DEL*/, 'Cut' ],
[ CTRL + 90 /*Z*/, 'Undo' ],
[ CTRL + 89 /*Y*/, 'Redo' ],
[ CTRL + SHIFT + 90 /*Z*/, 'Redo' ],
[ CTRL + 76 /*L*/, 'Link' ],
[ CTRL + 66 /*B*/, 'Bold' ],
[ CTRL + 73 /*I*/, 'Italic' ],
[ CTRL + 85 /*U*/, 'Underline' ],
[ CTRL + SHIFT + 83 /*S*/, 'Save' ],
[ CTRL + ALT + 13 /*ENTER*/, 'FitWindow' ]
] ;
/*
FCKConfig.ContextMenu = ['Generic','Link','Anchor','Image','Flash','Select','Textarea','Checkbox','Radio','TextField','HiddenField','ImageButton','Button','BulletedList','NumberedList','Table','Form'] ;
*/
//右键菜单的内容
FCKConfig.ContextMenu = ['Generic','Anchor','Select','Textarea','Checkbox','Radio','TextField','HiddenField','Button','BulletedList','NumberedList','Table','Form'] ;
FCKConfig.BrowserContextMenuOnCtrl = false ;
FCKConfig.EnableMoreFontColors = true ;
//文字颜色列表
FCKConfig.FontColors = '000000,993300,333300,003300,003366,000080,333399,333333,800000,FF6600,808000,808080,008080,0000FF,666699,808080,FF0000,FF9900,99CC00,339966,33CCCC,3366FF,800080,999999,FF00FF,FFCC00,FFFF00,00FF00,00FFFF,00CCFF,993366,C0C0C0,FF99CC,FFCC99,FFFF99,CCFFCC,CCFFFF,99CCFF,CC99FF,FFFFFF' ;
//文字格式列表
FCKConfig.FontFormats = 'p;h1;h2;h3;h4;h5;h6;pre;address;div' ;
//字体列表
FCKConfig.FontNames = '宋体;黑体;隶书;楷体_GB2312;Arial;Comic Sans MS;Courier New;Tahoma;Times New Roman;Verdana' ;
//字号列表
FCKConfig.FontSizes = 'smaller;larger;xx-small;x-small;small;medium;large;x-large;xx-large' ;
FCKConfig.StylesXmlPath = FCKConfig.EditorPath + 'fckstyles.xml' ; // CSS样式列表的XML文件的位置
FCKConfig.TemplatesXmlPath = FCKConfig.EditorPath + 'fcktemplates.xml' ; // 模版的XML文件位置
FCKConfig.SpellChecker = 'ieSpell' ; // 'ieSpell' | 'SpellerPages' 拼写检查器
FCKConfig.IeSpellDownloadUrl = 'http://www.iespell.com/download.php' ; // 下载拼写检查器的网址
FCKConfig.SpellerPagesServerScript = 'server-scripts/spellchecker.php' ; // Available extension: .php .cfm .pl
FCKConfig.FirefoxSpellChecker = false ;
FCKConfig.MaxUndoLevels = 15 ;
FCKConfig.DisableObjectResizing = false ;
FCKConfig.DisableFFTableHandles = true ;
FCKConfig.LinkDlgHideTarget = false ;
FCKConfig.LinkDlgHideAdvanced = false ;
FCKConfig.ImageDlgHideLink = false ;
FCKConfig.ImageDlgHideAdvanced = false ;
FCKConfig.FlashDlgHideAdvanced = false ;
FCKConfig.ProtectedTags = '' ;
// This will be applied to the body element of the editor
FCKConfig.BodyId = '' ;
FCKConfig.BodyClass = '' ;
FCKConfig.DefaultStyleLabel = '' ;
FCKConfig.DefaultFontFormatLabel = '' ;
FCKConfig.DefaultFontLabel = '' ;
FCKConfig.DefaultFontSizeLabel = '' ;
FCKConfig.DefaultLinkTarget = '' ;
// The option switches between trying to keep the html structure or do the changes so the content looks like it was in Word
FCKConfig.CleanWordKeepsStructure = false ;
// Only inline elements are valid.
FCKConfig.RemoveFormatTags = 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var' ;
// Attributes that will be removed
FCKConfig.RemoveAttributes = 'class,style,lang,width,height,align,hspace,valign' ;
FCKConfig.CustomStyles =
{
'Red Title' : { Element : 'h3', Styles : { 'color' : 'Red' } }
};
// Do not add, rename or remove styles here. Only apply definition changes.
FCKConfig.CoreStyles =
{
// Basic Inline Styles.
'Bold' : { Element : 'strong', Overrides : 'b' },
'Italic' : { Element : 'em', Overrides : 'i' },
'Underline' : { Element : 'u' },
'StrikeThrough' : { Element : 'strike' },
'Subscript' : { Element : 'sub' },
'Superscript' : { Element : 'sup' },
// Basic Block Styles (Font Format Combo).
'p' : { Element : 'p' },
'div' : { Element : 'div' },
'pre' : { Element : 'pre' },
'address' : { Element : 'address' },
'h1' : { Element : 'h1' },
'h2' : { Element : 'h2' },
'h3' : { Element : 'h3' },
'h4' : { Element : 'h4' },
'h5' : { Element : 'h5' },
'h6' : { Element : 'h6' },
// Other formatting features.
'FontFace' :
{
Element : 'span',
Styles : { 'font-family' : '#("Font")' },
Overrides : [ { Element : 'font', Attributes : { 'face' : null } } ]
},
'Size' :
{
Element : 'span',
Styles : { 'font-size' : '#("Size","fontSize")' },
Overrides : [ { Element : 'font', Attributes : { 'size' : null } } ]
},
'Color' :
{
Element : 'span',
Styles : { 'color' : '#("Color","color")' },
Overrides : [ { Element : 'font', Attributes : { 'color' : null } } ]
},
'BackColor' : { Element : 'span', Styles : { 'background-color' : '#("Color","color")' } },
'SelectionHighlight' : { Element : 'span', Styles : { 'background-color' : 'navy', 'color' : 'white' } }
};
// The distance of an indentation step.
FCKConfig.IndentLength = 40 ;
FCKConfig.IndentUnit = 'px' ;
// Alternatively, FCKeditor allows the use of CSS classes for block indentation.
// This overrides the IndentLength/IndentUnit settings.
FCKConfig.IndentClasses = [] ;
// [ Left, Center, Right, Justified ]
FCKConfig.JustifyClasses = [] ;
// The following value defines which File Browser connector and Quick Upload
// "uploader" to use. It is valid for the default implementaion and it is here
// just to make this configuration file cleaner.
// It is not possible to change this value using an external file or even
// inline when creating the editor instance. In that cases you must set the
// values of LinkBrowserURL, ImageBrowserURL and so on.
// Custom implementations should just ignore it.
//上传设置。第一个是文件浏览器使用的语言,第二个快速上传使用的语言,改成你需要的,JSP项目这里就不要改了
var _FileBrowserLanguage = 'php' ; // asp | aspx | cfm | lasso | perl | php | py
var _QuickUploadLanguage = 'php' ; // asp | aspx | cfm | lasso | perl | php | py
// Don't care about the following two lines. It just calculates the correct connector
// extension to use for the default File Browser (Perl uses "cgi").
var _FileBrowserExtension = _FileBrowserLanguage == 'perl' ? 'cgi' : _FileBrowserLanguage ;
var _QuickUploadExtension = _QuickUploadLanguage == 'perl' ? 'cgi' : _QuickUploadLanguage ;
FCKConfig.LinkBrowser = true ;
FCKConfig.LinkBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Connector=connectors/jsp/connector';
FCKConfig.LinkBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; // 70%
FCKConfig.LinkBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; // 70%
FCKConfig.ImageBrowser = false ; //是否在插入图片功能里面启用服务器文件浏览功能
FCKConfig.ImageBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Type=Image&Connector=connectors/jsp/connector'; //Type=Image 表示文件类型是image这会使文件浏览器定位到文件上传路径/image/文件夹下面
FCKConfig.ImageBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; // 70% ;
FCKConfig.ImageBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; // 70% ;
FCKConfig.FlashBrowser = false ; //是否在插入flash功能中启用服务器文件浏览功能
FCKConfig.FlashBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Type=Flash&Connector=connectors/jsp/connector';
FCKConfig.FlashBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; //70% ;
FCKConfig.FlashBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; //70% ;
FCKConfig.LinkUpload = true ; //是否启用插入链接的快速上传功能
FCKConfig.LinkUploadURL = FCKConfig.BasePath + 'filemanager/upload/simpleuploader?Type=File';
//这是两个允许和拒绝上传的文件类型列表
FCKConfig.LinkUploadAllowedExtensions = ".(7z|aiff|asf|avi|bmp|csv|doc|fla|flv|gif|gz|gzip|jpeg|jpg|mid|mov|mp3|mp4|mpc|mpeg|mpg|ods|odt|pdf|png|ppt|pxd|qt|ram|rar|rm|rmi|rmvb|rtf|sdc|sitd|swf|sxc|sxw|tar|tgz|tif|tiff|txt|vsd|wav|wma|wmv|xls|xml|zip)$" ; // empty for all
FCKConfig.LinkUploadDeniedExtensions = "" ; // empty for no one
FCKConfig.ImageUpload = true ; //是否启用图片快速上传功能
FCKConfig.ImageUploadURL = FCKConfig.BasePath + 'filemanager/upload/simpleuploader?Type=Image';
FCKConfig.ImageUploadAllowedExtensions = ".(jpg|gif|jpeg|png|bmp)$" ; // empty for all
FCKConfig.ImageUploadDeniedExtensions = "" ; // empty for no one
FCKConfig.FlashUpload = true ; //是否启用flash上传功能
FCKConfig.FlashUploadURL = FCKConfig.BasePath + 'filemanager/upload/simpleuploader?Type=Flash';
FCKConfig.FlashUploadAllowedExtensions = ".(swf|flv)$" ; // empty for all
FCKConfig.FlashUploadDeniedExtensions = "" ; // empty for no one
FCKConfig.SmileyPath = FCKConfig.BasePath + 'images/smiley/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 ; // 表情窗口显示高度,此窗口会因为表情文件的改变而作调整
FCKConfig.BackgroundBlockerColor = '#ffffff' ;
FCKConfig.BackgroundBlockerOpacity = 0.50 ;
遇到的问题和解决办法:
当我上传中文名图片时发现图片上传到指定文件夹下了,fck中显示的是X,而且通过url也访问不到图片很纳闷。有说是权限问题,还有的让更改tomcat下service.xml 的编码格式。觉得很麻烦,最后找到源码(下载的fckeditor-java-2.6-src.zip)解压找到 java-core\src\main\java\net\fckeditor\connector路径下的Dispatcher.java文件,在自己的 eclipse下建包net.fckeditor.connector,把Dispatcher.java复制进去。源码如下
String fileName = FilenameUtils.getName(uplFile.getName()); logger.debug("Parameter NewFile: {}", fileName);
一段,这里就是文件的名字。然后把它修改成
String fileName = FilenameUtils.getName(uplFile.getName()); String suffix = fileName.substring(fileName.lastIndexOf("."));//获得文件名后缀 fileName = UUID.randomUUID().toString(); fileName = fileName + suffix; logger.info("Parameter NewFile: {}", fileName);
很简单,就是用UUID作为自己的图片名称。然后编译出来, 直接到tomcat下找到该文件就成。并把该文件替换到工程 lib下的java-core-2.6.jar目录很好找不写了。重新部署工程这次上传图片可以是中文的了。
下面我把改好的整个需要的jar(里面的java-core-2.6.jar我已经修改)和例子附上。希望大家支持,在下菜鸟高手勿喷!!!
图片上传不成功,需要修改一下这里的路径,请用自己的路径,而不是我设置好的路径:
图片上传的配置
打开文件FCKeditor/editor/filemanager/browser/default/connectors/php/config.php:
查找$Config['Enabled'],将它设置为'true';查找$Config['UserFilesPath'],将它设置图片的目录,这个目录是相对于主目录的。
打开文件FCKeditor/editor/filemanager/upload/php/config.php:
查找$Config['Enabled'],将它设置为'true';查找$Config['UseFileType'],将它设置上传文件的目录,最好与上面的图片目录相同。