此代码是最新版的 KindEditor 3.5.x 实现本地图片上传的方法,用于oschina即将改版的个人空间
KindEditor 要求的JSON格式如下:
{"error":0,"message":".....","url":"/img/1111.gif"}
其中当error值为0时表示上传成功,需要指定url值为图片保存后的URL地址,如果error值不为0,则设置message值为错误提示信息
[代码]首先指定上传处理的URI
5 |
allowPreviewEmoticons : false , |
8 |
imageUploadJson : '/action/blog/upload_img' |
[代码]图片上传处理方法
06 | @Annotation .PostMethod |
07 | @Annotation .JSONOutputEnabled |
08 | public void upload_img(RequestContext ctx) throws IOException { |
09 |
File imgFile = ctx.image( "imgFile" ); |
10 |
if (imgFile.length() > MAX_IMG_SIZE ){ |
12 |
new String[]{ "error" , "message" }, |
13 |
new Object[]{ 1 ,ResourceUtils.getString( "error" , "file_too_large" , MAX_IMG_SIZE/ 1024 )} |
17 |
String uri = new SimpleDateFormat( "yyyyMMdd" ).format( new Date()) |
19 |
+ RandomStringUtils.randomAlphanumeric( 4 ) |
21 |
+ String.valueOf(ctx.user().getId()) |
23 |
+ FilenameUtils.getExtension(imgFile.getName()).toLowerCase(); |
25 |
Multimedia.saveImage(imgFile, img_path + uri, 0 , 0 ); |
26 |
ctx.output_json( new String[]{ "error" , "url" }, new Object[]{ 0 , LinkTool.upload( "space/" +uri)}); |
jsp 主页面code:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("UTF-8");
String htmlData = request.getParameter("content1") != null ? request.getParameter("content1") : "";
%>
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>KindEditor JSP</title>
<script type="text/javascript" charset="utf-8" src="../kindeditor.js"></script>
<script type="text/javascript">
KE.show({
id : 'content1',
imageUploadJson : '../../jsp/upload_json.jsp',
fileManagerJson : '../../jsp/file_manager_json.jsp',
allowFileManager : true,
afterCreate : function(id) {
KE.event.ctrl(document, 13, function() {
KE.util.setData(id);
document.forms['example'].submit();
});
KE.event.ctrl(KE.g[id].iframeDoc, 13, function() {
KE.util.setData(id);
document.forms['example'].submit();
});
}
});
</script>
</head>
<body>
<%=htmlData%>
<form name="example" method="post" action="demo.jsp">
<textarea id="content1" name="content1" cols="100" rows="8" style="width:700px;height:200px;visibility:hidden;"><%=htmlspecialchars(htmlData)%></textarea>
<br />
<input type="submit" name="button" value="æ交内容" /> (æ交快æ·é”®: Ctrl + Enter)
</form>
</body>
</html>
<%!
private String htmlspecialchars(String str) {
str = str.replaceAll("&", "&");
str = str.replaceAll("<", "<");
str = str.replaceAll(">", ">");
str = str.replaceAll("\"", """);
return str;
}
%>