本人文笔不好,也是菜鸟一只,如果是大神请绕道,目的只在于交流
这几天做的并且测试通过,给以后搞开发的朋友不必在这个地方纠结(没什么技术含量而且很花时间)。废话不说,直接进入主题
1. 首先要对kindeditor有一定的了解(最好下载一个API手册来看看)
在你的js文件中载入kindeditor:
//载入KindEditor
var editor1;
functionCreateKE(){
setTimeout(function(){
editor1 = KindEditor.create('#content_area',{ // content_area是下面textarea的id
uploadJson :'upload!receiveFile.action',//用于上传文件和图片的服务端,这是我的地址,(!receiveFile是struts2的方法动态调用,这个应该都知道吧,不必多说了)
//fileManagerJson: '/kindeditor/jsp/file_manager_json.jsp', //用于访问文件空间的服务端,没有实现注释的地址是kindeditor自带的。
allowFileManager :true,
afterBlur :function(){
this.sync();
},
items : [ 'source','|','undo','redo','|','preview','print',
'template','code','cut','copy','paste','plainpaste',
'wordpaste','|','justifyleft','justifycenter',
'justifyright','justifyfull','insertorderedlist',
'insertunorderedlist','indent','outdent','subscript',
'superscript','clearhtml','quickformat','selectall',
'|','fullscreen','/','formatblock','fontname',
'fontsize','|','forecolor','hilitecolor','bold',
'italic','underline','strikethrough','lineheight',
'removeformat','|','image','multiimage','insertfile',
'table','hr','emoticons','baidumap','pagebreak',
'anchor','link','unlink','|','about' ],
allowImageRemote :false, //隐藏网络图片功能
allowFileManager :false //隐藏访问文件空间功能
});
},500);
}
2.Ext.Form.Panel中的textarea中创建kindeditor编辑框
myPanel = new {
.
.
.
Items : [{ …} , {… } ,
{
xtype:'textarea',
id:'content_area', //这个就是上面editor的id
fieldLabel :'内容',
allowBlank :false,
blankText :'内容不能为空!',
name:'content',
height :450
}
] ,
listeners:{
'render':CreateKE
}
}
这下你的window里面就会有kindeditor编辑器了
3.文件和图片上传功能的实现
首先说一下kindeditor自带的上传服务端,upload_json.jsp。为什么我们不直接用这个呢?
开始我自己就用的这个服务端,当运行时发现,竟然在List items = upload.parseRequest(request); 这一步出现nullpointException line79
后来想了想找出了问题,在web.xml struts的配置是:
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
即对所有的请求都进行拦截。当前发请求到upload_json.jsp,实际上是经过了struts2的一系列拦截处理。通过HttpServletRequest req = ServletActionContext.getRequest()得到的request是包装之后的request不再是原来servlet中的请求对象。如果不进行拦截就要改为 <url-pattern>*.action</url-pattern>
如果为了将就一个编辑器而改变了web.xml的配置就太不应该了,所以还是自己写个处理上传的action吧!
这里说了点题外话,继续代码,以下是我的uploadAction.java,建议在看之前先去看看struts2对文件上传的处理(暴强,其他的都弱爆了)
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.struts2.ServletActionContext;
import org.json.simple.JSONObject;
/**
* 处理kindeditor编辑器上传的图片和文件
*
* @authorAdministrator
*
*/
public class UpLoadAction extends BaseAction {
privatestatic final int BUFFER_SIZE = 16 * 1024;
privateString dir; // kindeditor标识是图片还是文件的参数 (值是image或者file)
privateString localUrl; // 图片的文件名;文件和多张图片上传没有这个参数
privateFile[] imgFile; // 图片文件内容
privateString[] imgFileFileName;//图片文件名字
/**
* 接收图片,多图片,文件上传的处理
* @throws IOException
*/
public voidreceiveFile() throws IOException {
req.setCharacterEncoding("utf-8");
res.setCharacterEncoding("utf-8");
//最大文件大小
longmaxSize = 1024 * 1024 * 10;
//文件保存目录路径
StringsavePath = ServletActionContext.getRequest().getRealPath("/")
+"attached/";
//文件保存目录URL
StringsaveUrl = ServletActionContext.getRequest().getContextPath()
+"/attached/";
//定义允许上传的文件扩展名
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,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
extMap.put("file","doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
if(!ServletFileUpload.isMultipartContent(req)) {
res.getWriter().write(getError("请选择文件。"));
return;
}
//检查目录
FileuploadDir = new File(savePath);
if(!uploadDir.isDirectory()) {
res.getWriter().write(getError("上传目录不存在。"));
return;
}
//检查目录写权限
if(!uploadDir.canWrite()) {
res.getWriter().write(getError("上传目录没有写权限。"));
return;
}
if(dir == null) {
dir= "image";
}
if(!extMap.containsKey(dir)) {
res.getWriter().write(getError("目录名不正确。"));
return;
}
//创建文件夹
savePath+= dir + "/";
saveUrl+= dir + "/";
FilesaveDirFile = new File(savePath);
if(!saveDirFile.exists()) {
saveDirFile.mkdirs();
}
SimpleDateFormatsdf = new SimpleDateFormat("yyyyMMdd");
Stringymd = sdf.format(new Date());
savePath+= ymd + "/";
saveUrl+= ymd + "/";
FiledirFile = new File(savePath);
if(!dirFile.exists()) {
dirFile.mkdirs();
}
//为上传的图片或文件重命名并保存在服务器上
for(inti=0;i<imgFile.length;i++){
Filefile = imgFile[i];
StringfileName = imgFileFileName[i];
longfileSize = file.length();
//检查文件大小
if(fileSize > maxSize) {
res.getWriter().write(getError("上传文件大小超过限制。"));
return;
}
StringfileExt = null;
//检查扩展名
if(localUrl!=null){
fileExt= localUrl.split("\\.")[1].toLowerCase();
}else{
fileExt= fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
}
//System.out.println("fileName: "+fileName);
if(!Arrays.<String> asList(extMap.get(dir).split(","))
.contains(fileExt)){
res.getWriter().write(
getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dir)
+"格式。"));
return;
}
SimpleDateFormatdf = new SimpleDateFormat("yyyyMMddHHmmss");
StringnewFileName = df.format(new Date()) + "_"
+new Random().nextInt(1000) + "." + fileExt;
try{
FileuploadedFile = new File(savePath, newFileName);
copy(file,uploadedFile);
}catch (Exception e) {
res.getWriter().write(getError("上传文件失败。"));
return;
}
JSONObjectobj = new JSONObject();
obj.put("error",0); //正确时返回的json数据
obj.put("url",saveUrl + newFileName);
System.out
.println("obj.toJSONString(): " + obj.toJSONString());
res.getWriter().write(obj.toJSONString());
}
}
/**
* 自己封装的一个把源文件对象复制成目标文件对象
* @param src
* @param dst
*/
private static void copy(File src, File dst){
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(newFileInputStream(src), BUFFER_SIZE);
out = new BufferedOutputStream(newFileOutputStream(dst),
BUFFER_SIZE);
byte[] buffer = newbyte[BUFFER_SIZE];
int len = 0;
while ((len = in.read(buffer)) >0) {
out.write(buffer, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 向前台发送错误显示的json字符子串格式
* @param message
* @return
*/
privateString getError(String message) {
JSONObjectobj = new JSONObject(); // JSONObject是json_simple1-1包中的
obj.put("error",1);
obj.put("message",message);
returnobj.toJSONString();
}
publicString getLocalUrl() {
returnlocalUrl;
}
public voidsetLocalUrl(String localUrl) {
this.localUrl= localUrl;
}
public StringgetDir() {
returndir;
}
public voidsetDir(String dir) {
this.dir= dir;
}
public voidsetImgFile(File[] imgFile) {
this.imgFile= imgFile;
}
publicFile[] getImgFile() {
returnimgFile;
}
public voidsetImgFileFileName(String[] imgFileFileName) {
this.imgFileFileName= imgFileFileName;
}
publicString[] getImgFileFileName() {
returnimgFileFileName;
}
}
注意及说明:1.创建editor时,是#+id “#content_area”.
2.请确保有这三个jar包:
* commons-fileupload-1.2.1.jar
* commons-io-1.4.jar
* json_simple-1.1.jar
3.图片和文件保存在comcat目录的你的webapp目录中
4.还有问题的请联系我本人QQ1196502672,进行交流与讨论~!