ckeditor+jsp+spring配置图片上传

时间:2023-03-08 23:24:16
ckeditor+jsp+spring配置图片上传

CKEditor用于富文本输入是极好的,它还有一些插件支持扩展功能,其中图片上传就是比较常用到的。本文简单记录我的实现步骤。

1.CKEditor除了提供三种标准版压缩包下载,还可根据自己的需求进行个性化打包下载。无论采取何种方式,从CKEditor官网下载带ImgUpload功能的压缩包,解压放在web工程resource目录下,例如我是放在:

webapp/resources/ckeditor

2.CKEditor配置文件(java):

 import com.ckeditor.CKEditorConfig;
import com.ckeditor.EventHandler;
import com.ckeditor.GlobalEventHandler; public class CKEditorHelper
{
public static CKEditorConfig createConfig() {
CKEditorConfig config = new CKEditorConfig(); config.addConfigValue("filebrowserImageUploadUrl","uploadImg");//uploadImg是处理上传图片的url return config;
} public static EventHandler createEventHandlers() {
EventHandler handler = new EventHandler();
return handler;
} public static GlobalEventHandler createGlobalEventHandlers() {
GlobalEventHandler handler = new GlobalEventHandler();
return handler;
}
}

3.处理上传图片(java),随便写在一个controller里

@RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
public ModelAndView uploadImg(@RequestParam("upload") CommonsMultipartFile upload,
String CKEditor,String CKEditorFuncNum,String langCode,
HttpServletResponse response) {
// System.out.println("-----file name is :" + file.getOriginalFilename());
String currentFileName= String.valueOf(System.currentTimeMillis());
String url="";
if (!upload.isEmpty()) {
String picId = UtilDate.getID();
try {
FileHelper.saveImg(upload, picId);
} catch (IOException e) {
e.printStackTrace();
}
url="getImg?imgId="+picId;
} // return "<script>window.opener.CKEDITOR.tools.callFunction( "+CKEditorFuncNum+", "+ url+" );</script>" ;
String message = "成功上传图片"+upload.getOriginalFilename();
try {
response.setContentType("text/html; charset=gbk");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<script type=\"text/javascript\">");
out.println("//<![CDATA[");
String call = "window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ",'" + StringEscapeUtils.escapeJavaScript(url)
+ "'" + (message != null ? ",'" + StringEscapeUtils.escapeJavaScript(message) + "'" : "") + ");";
out.println(call);
out.println("//]]>");
out.println("</script>");
out.println("</html>");
} catch (Exception e) {
e.printStackTrace();
}
return null; }

4.页面配置(jsp):这里只列出关键代码。这段代码的意思是,将id="content"的textarea替换为ckeditor的输入框,其配置文件为CKEditorHelper,资源文件为resources/ckeditor/

注意:前两行代码放在<HTML>标签之前,其他随意

 <%@ taglib uri="http://ckeditor.com" prefix="ckeditor" %>
<%@ page import="CKEditorHelper" %> <form:textarea class="form-control" path="content" placeholder="内容" name="content" rows="5"/> <ckeditor:replace replace="content" basePath="resources/ckeditor/"
config="<%= CKEditorHelper.createConfig() %>"
events="<%= CKEditorHelper.createEventHandlers() %>"/> <script src="resources/ckeditor/ckeditor.js"></script>