富文本编辑器,在我们web开发项目中是经常使用的第三方的API在经过两天的研究后,彻底整的透透彻彻。
在页面中引入依赖文件(使用绝对路径)注意需要修改:上传文件的路径
<script type="text/javascript" src="<%=request.getContextPath() %>/admin/js/bootstrap.min.js" ></script>
<link rel="stylesheet" href="<%=request.getContextPath()%>/kindeditor/themes/default/default.css" />
<script charset="utf-8" src="<%=request.getContextPath()%>/kindeditor/kindeditor.js"></script>
<script charset="utf-8" src="<%=request.getContextPath()%>/kindeditor/lang/zh_CN.js"></script>
<script type="text/javascript">
var editor;
KindEditor.ready(function(K) {
editor = K.create('textarea[name="bcontent"]', {
uploadJson : "<%=request.getContextPath()%>/BookServlet?method=kindupload",
allowFileManager : true,
allowImageUpload: true, //多图上传
allowFileManager : true, //浏览图片空
filterMode : false, //HTML特殊代码过滤
afterBlur: function(){ this.sync(); }, //编辑器失去焦点(blur)时执行的回调函数(将编辑器的HTML数据同步到textarea)
});
prettyPrint();
});
</script>
在需要展示的位置添加
<div class="layui-input-block">
<textarea name="content" style="width:800px;height:400px;visibility:hidden;">KindEditor</textarea>
</div>
Servlet(需要注意的是,该文件是保存在服务器中的,需要增加fileUtils.copy拷贝到项目路径)
protected void kindupload(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter writer = response.getWriter();
try {
// 文件保存目录路径
String savePath = request.getServletContext().getRealPath("/upload/");
String saveUrl = request.getContextPath() + "/upload/";
response.setContentType("text/html; charset=UTF-8");
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
String fileName = item.getName();
if (!item.isFormField()) {
// 检查扩展名
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
File uploadedFile = new File(savePath, newFileName);
item.write(uploadedFile);
System.out.println("上传文件成功:" + newFileName);
JSONObject obj = new JSONObject();
obj.put("error", 0);
obj.put("url", saveUrl + newFileName);
writer.println(obj.toString());
writer.flush();
writer.close();
}
}
} catch (Exception ex) {
ex.printStackTrace();
return;
}
}
private String getError(String message) { JSONObject obj = new JSONObject(); obj.put("error", 1); obj.put("message", message); return obj.toString(); }
在jsp页面进行展示的时候,直接写就Ol了,如果没有显示出来,在浏览器F12看下,找的地址是否正确,不正确则,上传地址有误,正确的话,刷新一下项目路径,服务器路径即可解决