从众多的Web编辑器中选择KindEditor ,主要是看重它的小巧。一个JS文件、两个CSS文件和一个GIF图片就是它的全部。所以在页面上的加载速度很快,而且功能也相对齐全。
目前KindEditor自带的图片上传组件仅仅是对PHP的支持,但是我的项目用到了Struts2,所以图片上传这一块还需要自己来写。
首先,修改plugins目录下的image.html文件,将form的action改为:
action="/imageUpload"
并且在
<input type="hidden" id="editorId" name="id" value="" />
中的value属性设置为你页面上编辑器的id。
这个地址对应的是一个Action,在Struts2中的配置为:
<action name="imageUpload" class="com.bjqxwh.manage.web.KindEditorImageUploadAction"> <result name="success">/editor/imageUploadSuccess.jsp</result> <result name="error">/editor/imageUploadError.jsp</result> </action>
具体代码如下:
package com.bjqxwh.manage.web;
import java.io.File;
import org.apache.struts2.ServletActionContext;
import com.bjqxwh.manage.service.UploadService;
import com.opensymphony.xwork2.ActionSupport;
/**
* 处理从KindEditor编辑器中上传的图片
*
* @author shelltea
*
*/
public class KindEditorImageUploadAction extends ActionSupport {
private static final long serialVersionUID = 920697011722287589L;
private String savePath = "/editor/upload";
private File imgFile;
private String imgFileContentType;
private String imgFileFileName;
private String id;
private String imgTitle;
private String imgWidth;
private String imgHeight;
private String imgBorder;
private String saveUrl;
// 省略Setter和Getter方法
@Override
public String execute() throws Exception {
saveUrl = UploadService.upload(imgFile, imgFileFileName, savePath,
ServletActionContext.getRequest());
// 针对FireFox自动将绝对地址转换为相对地址的,将保持的URL改为相对地址
String[] s = saveUrl.split("/");
saveUrl = "/" + s[3] + "/" + s[4] + "/" + s[5];
return SUCCESS;
}
}
这段代码中的UploadService是我自己写的一个上传服务组件,通过调用upload方法上传文件,并返回在服务器上的绝对地址。但是直接返回的绝对地址在FireFox中自动转换为了相对地址。这就给编辑带来的不便,在编辑时编辑器中显示不出图片,问题就处在地址上,所以干脆将地址直接转换为相对地址来解决这个问题。
然后是写一个上传成功后的页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert image</title>
</head>
<body>
<script language="javascript" type="text/javascript">
parent.KE.plugin["image"].insert("${id}","${saveUrl}","${imgTitle}","${imgWidth}","${imgHeight}","${imgBorder}");
</script>
</body>
</html>