近期实现了项目整合ckeditor,包括上传图片,粘贴上传图片,内容保存及展示等功能;遇到了蛮多坑,简单总结一下。
效果展示:
1.下载ckeditor
https://ckeditor.com/ckeditor-4/download/
注意:这里有好几个版本,你可以根据需要下载,我刚开始下载中间的标准版,然后没有很多按钮,包括保存按钮;
后面就改下了Full Package这个版本;建议大家也直接下载这个版本,反正也大不了多少。
2.前台代码
我这里用了form表单,因为我要把富文本中内容存入数据库,
<body class="ui-widget-content">
<form id="uploadFile" method="post" enctype="multipart/form-data" "return false" action="home/home_uploadfile.action">
<table class="wbs-bordered" style="width:100%" id="projecttb">
<tr >
<td colspan="4" rowspan="10" > <textarea class="ckeditor" name="form.description" id="description" /></textarea></td>
</tr>
</table>
</form>
<script type="text/javascript">
jQuery(function(){
// 定义富文本高度为浏览器高度的80%,大家可以根据自己需要更改
var screenHeight = $(window).height();
var height = screenHeight * 0.8;
var editor = CKEDITOR.replace('description',{
height: height
});
// selectFile方法用来初始化富文本页面时从数据库中查询富文本内容,展示出来
$.ajax({
url: 'home/home_selectFile.action',
type: 'POST',
async: false,
data: { "form.fileid": 24 },
success: function(data){
var form = data.form;
var json = $.wbsToJson(form.dataJson);
var fileShow = json.fileShow;
$("#description").val(fileShow);
}
});
//重写了ckeditor的save按钮关联的方法
editor.on('instanceReady', function(){
//保存
this.addCommand("save", {
modes : {
wysiwyg : 1,
source : 1
},
exec : function(editor) {
save();
}
});
});
function save(){
var content = editor.getData();
$("#description").val(content);
$("#uploadFile").ajaxSubmit(function(data) {
});
}
});
</script>
</body>
3.修改ckeditor配置文件config.js文件
这个文件你可以根据自己需要就行修改,在你下载的ckeditor插件包里面有一个samples文件夹,打开里面的index.html文件,可以根据需要配置你的富文本工具栏界面:
1.打开index.html页面后,点击如下文本
2.设置你想要的工具栏:将设置后的代码复制到config.js文件中即可
config.js代码如下:这里是我自己采用的配置,你可以根据需要来配置自己的界面
注意:上传图片的action一定要配置!!!
CKEDITOR.editorConfig = function( config ) {
config.image_previewText=' '; //情空预览区域显示内容
config.filebrowserImageUploadUrl= "/jjfp/home/home_imgUpload.action"; //待会要上传的action或servlet
config.imageUploadUrl = "/jjfp/home/home_imgUpload.action"; //粘贴图片上传的action或servlet
config.toolbarGroups = [
{ name: 'document', groups: [ 'mode', 'document', 'doctools' ] },
{ name: 'clipboard', groups: [ 'clipboard', 'undo' ] },
{ name: 'forms', groups: [ 'forms' ] },
{ name: 'editing', groups: [ 'find', 'selection', 'spellchecker', 'editing' ] },
{ name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi', 'paragraph' ] },
{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
{ name: 'links', groups: [ 'links' ] },
{ name: 'insert', groups: [ 'insert' ] },
{ name: 'styles', groups: [ 'styles' ] },
{ name: 'colors', groups: [ 'colors' ] },
{ name: 'tools', groups: [ 'tools' ] },
{ name: 'others', groups: [ 'others' ] },
{ name: 'about', groups: [ 'about' ] }
];
config.removeButtons = 'Copy,Paste,Undo,Redo,Anchor,Underline,Strike,Subscript,Superscript,Source,Cut,ImageButton,Button,HiddenField,Radio,Checkbox,CreateDiv,Unlink,Flash,Iframe,About,ShowBlocks,NewPage,Templates';
config.removeDialogTabs = 'image:advanced;link:advanced';
};
4.如果点击图片,上传按钮不显示,如下设置:(我这里没有这个问题,大家根据自己需要修改)
5.后台代码:
注意:此处返回的代码不同的版本不同,之前老的版本,返回的是script等前台html标签代码;新版本返回的是json格式的数据;
可以查询ckeditor官方文档:https://ckeditor.com/docs/ckeditor4/latest/guide/dev_file_upload.html
另外下面的代码大部分是我抄的其它网友的,不过忘了是哪位写的了,这里就不贴原文链接了,尴尬~~~
/**
*
* 图片上传代码,图片会保存到tomcat下的\img\uploadImg文件夹下
* @return
* @throws IOException
*/
public String imgUpload() throws IOException {
// 获得response,request
HttpServletResponse response = ServletActionContext.getResponse();
HttpServletRequest request = ServletActionContext.getRequest();
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
// CKEditor提交的很重要的一个参数
String expandedName = ""; // 文件扩展名
JSONObject result = new JSONObject();
Map<String, Object> msgMap = new HashMap<>();
String msg = "";
if (uploadContentType.equals("image/pjpeg") || uploadContentType.equals("image/jpeg")) {
// IE6上传jpg图片的headimageContentType是image/pjpeg,而IE9以及火狐上传的jpg图片是image/jpeg
expandedName = ".jpg";
} else if (uploadContentType.equals("image/png")
|| uploadContentType.equals("image/x-png")) {
// IE6上传的png图片的headimageContentType是"image/x-png"
expandedName = ".png";
} else if (uploadContentType.equals("image/gif")) {
expandedName = ".gif";
} else if (uploadContentType.equals("image/bmp")) {
expandedName = ".bmp";
} else {
msg = "文件格式不正确(必须为.jpg/.gif/.bmp/.png文件)";
result.put("uploaded", 0);
msgMap.put("message", msg);
result.put("error", msgMap);
out.println(result.toJSONString());
return null;
}
if (upload.length() > 600 * 1024) {
msg = "文件大小不得大于600k";
result.put("uploaded", 0);
msgMap.put("message", msg);
result.put("error", msgMap);
out.println(result.toJSONString());
return null;
}
InputStream is = new FileInputStream(upload);
//图片上传路径
String uploadPath = ServletActionContext.getServletContext().getRealPath("/img/uploadImg");
String fileName = java.util.UUID.randomUUID().toString(); // 采用时间+UUID的方式随即命名
fileName += expandedName;
File file = new File(uploadPath);
if (!file.exists()) { // 如果路径不存在,创建
file.mkdirs();
}
File toFile = new File(uploadPath, fileName);
OutputStream os = new FileOutputStream(toFile);
byte[] buffer = new byte[1024];
int length = 0;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
is.close();
os.close();
// 返回"图像"选项卡并显示图片 request.getContextPath()为web项目名
String imageUrl = request.getContextPath() + "/img/uploadImg/" + fileName;
//上传成功,返回成功提示
result.put("uploaded", 1);
result.put("filename", fileName);
result.put("url", imageUrl);
out.println(result.toJSONString());
return null;
}
/**
* 初始化富文本内容代码,从数据库查询保存的最后一条数据
*/
@Override
public void selectFile(HomeForm form) {
String sql = "select t.fileid, t.fileshow from ta_file t ORDER BY t.fileid desc limit 1";
List<Map<String, Object>> list = queryForList(sql);
String fileShow = list.get(0).get("fileshow").toString();
JSONObject json = new JSONObject();
json.put("fileShow", fileShow);
form.setDataJson(json.toJSONString());
}
整个过程花了蛮长时间,不过总体好像不是很难,嘿嘿。