CKeditor4.9.2最新图片上传配置

最近在弄CKeditor富文本编辑器,到上传图片的配置这一步时,发现网上的教程都不适合我现在的版本,于是决定自己上官网看相关的文档,好在有浏览器帮我自动翻译了网页,很快我便找到了图片上传的配置,下面是相关教程。

第一步:下载CKeditor(这不废话吗?),本文针对的版本是CKeditor-4.9.2,其他版本没有试过。

第二步:解压下载好的压缩包,放到自己的应用目录下,在config.js的CKEDITOR.editorConfig = function( config ) {}中加入如下全局配置:

/*将编辑器的语言设置为中文*/
config.language = 'zh-cn';
/*去掉图片预览框的文字*/
config.image_previewText = ' ';
/*开启工具栏“图像”中文件上传功能,后面的url为图片上传要指向的的action或servlet*/
config.filebrowserImageUploadUrl= "/blog/uploadEditorImage";

第三步:在要使用CKeditor的html中引入如下js

<script src="ckeditor-4.9.2/ckeditor.js" type="text/javascript" charset="utf-8"></script>
<script src="ckeditor-4.9.2/config.js" type="text/javascript" charset="utf-8"></script>

第四步:在html中使用CKeditor

<textarea id="content">Hello World</textarea>
		
<script type="text/javascript">
    CKEDITOR.replace('content',{
	removePlugins:'elementspath,resize',
	codeSnippet_theme: 'zenburn',
	height:'300'
    });
</script>

第五步:服务器端(Java)上传图片配置,这里要特别注意,此版本的CKeditor在图片上传成功后不再使用window.parent.CKEDITOR.tools.callFunction了,而是返回一个json字符串对象:

    上传成功时,返回:

        {

            "uploaded":1,

            "fileName":"图片名称",

            "url":"图片访问路径"

        }

    上传失败时,返回

            {

                    "uploaded":0,

            "error":{

                "message":"失败原因"

            }

            }

以下服务器端的完整代码

	@RequestMapping("/uploadEditorImage")
	public void uploadEditorImage(HttpServletResponse response, HttpServletRequest request,@RequestParam("upload")MultipartFile file) {
		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());
		}


猜你喜欢

转载自blog.csdn.net/genaro26/article/details/80871225