简单记录下使用方式:
页面使用textarea元素作为容器:
<textarea id="content" name="content" ></textarea>
使用Kindeditor的js渲染textarea,生成一个富文本编辑框(并不是原来的textarea)
$(function(){
KindEditor.create('#content',{
height : '500px',
newlineTag : 'br',
allowPreviewEmoticons : false,
allowImageUpload : true, //允许上传图片
allowFileUpload :true,//允许上传附件
filterMode : false,
uploadJson : '${rc.contextPath}/kindeditor/upload.do',
resizeType : 0,
items : [],//操作按钮,根据需求选择,这里省略
afterBlur : function() {
this.sync();
}
});
});
文件上传:
uploadJson : '${rc.contextPath}/kindeditor/upload.do',
uploadJson属性指定了文件上传的请求路径,
处理程序需要返回约定结构的JSON数据,Kindeditor已经写好了解析程序,
//成功的情况
JSONObject returnMap = new JSONObject();
returnMap.put("error", 0);
returnMap.put("url", path);
return returnMap;
error:0表示上传成功,url为文件存储路径,例如,如果上传图片,返回的url会作为image元素的src属性,在富文本编辑框作显示
处理程序示例:
@ResponseBody
@RequestMapping("/upload.do")
public Object addNoticeImage(HttpServletRequest request,HttpServletResponse response)
throws UnsupportedEncodingException, IOException, FileUploadException {
HashMap<String, String> extMap = new HashMap<String, String>();
extMap.put("image", "gif,jpg,jpeg,png,bmp");
extMap.put("flash", "swf,flv");
extMap.put("media", "swf,flv,mp3,mp4,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2,pdf");
//图片上传上限
long maxSize = 50000000;
String dirName = request.getParameter("dir");
if (dirName == null) {
dirName = "image";
}
//json数据容器
JSONObject returnMap = new JSONObject();
MultipartHttpServletRequest multipartRequest =
(MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile("imgFile");
if(file.getSize() > maxSize){
returnMap.put("message","上传文件大小超过限制。");
returnMap.put("error", 1);
return returnMap;
}
String originalFilename = file.getOriginalFilename();
String fileExt = originalFilename.substring(
originalFilename.lastIndexOf(".") + 1).toLowerCase();
if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){
returnMap.put("message", "上传文件扩展名是不允许的扩展名。\n只允许" +
extMap.get(dirName) + "格式。");
returnMap.put("error", 1);
return returnMap;
}
try{
String path = QiNiuUtil.doUpload(file);
returnMap.put("error", 0);
returnMap.put("url", path);
return returnMap;
}catch(Exception e){
e.printStackTrace();
}
returnMap.put("error", 1);
returnMap.put("message", "程序异常");
return returnMap;
}