CKeditor-4.10.0富文本编辑器,到上传图片的配置,网上的教程都不适合现在的版本。
第一步:在config.js的CKEDITOR.editorConfig = function( config ) {}中加入如下全局配置:
config.language = 'zh-cn';/*将编辑器的语言设置为中文*/
config.image_previewText = ' ';/*去掉图片预览框的文字*/
/*开启工具栏“图像”中文件上传功能,后面的url为图片上传要指向的的action或servlet*/
config.filebrowserImageUploadUrl= "/blog/uploadEditorImage";
第二步:为了提高可扩展性,也可在引入CKeditor的页面配置
var editor = CKEDITOR.replace('pcContent',{
filebrowserImageUploadUrl : '${rc.contextPath}/upload/${systemId}/article/image_upload.htm?id=${articleId!}'+'&useScene='+useScenePc,
language : 'zh-cn',
…………其他属性略
});
第三步:在要使用CKeditor的html中引入如下js
第四步:服务器端(Java)上传图片配置,这里要特别注意,此版本的CKeditor在图片上传成功后不再使用window.parent.CKEDITOR.tools.callFunction了,而是返回一个json字符串对象:
上传成功时,返回:
{
"uploaded":1,
"fileName":"图片名称",
"url":"图片访问路径"
}
上传失败时,返回
{
"uploaded":0,
"error":{
"message":"失败原因"
}
}
以下服务器端的完整代码
PrintWriter out = null;
String imageUrl = "";
String msg = "";
String fileName = "";
JSONObject result = new JSONObject();
try {
out = response.getWriter();
String imagesViewUrlPrefix = CommonResource.get("imagesViewUrlPrefix");
String fileType = FileUtil.getFileSuffixFromContentType(file.getContentType());
fileName = UUIDFactory.getUUID() + "." + fileType;
BaseResult uploadResult = FileUtil.uploadFile(fileName, file.getInputStream());
if(uploadResult.getCode() == ResultType.CODE_NORMAL) {
String imagePath = (String) uploadResult.getData();
imageUrl = imagesViewUrlPrefix + imagePath;
}else {
msg = "文件上传失败";
}
} catch (Exception e) {
e.printStackTrace();
logger.error("富文本编辑器上传图片时发生异常", e);
msg = "服务器异常";
} finally {
if(!StringUtil.isNullOrEmpty(msg)) {
//上传失败
result.put("uploaded", 0);
JSONObject errorObj = new JSONObject();
errorObj.put("message", msg);
result.put("error", errorObj);
}else {
//上传成功
result.put("uploaded", 1);
result.put("fileName", fileName);
result.put("url", imageUrl);
}
out.println(result.toJSONString());