您的位置:首页 > 编程语言 > Java开发

EasyUI+Struts2整合KindEditor

2013-10-18 12:50 561 查看
EasyUI整合KindEditor:

<%@ page language="java"  pageEncoding="UTF-8"%>
<script>
var editor;
$(function(){
var options = {
themeType : 'default',   //指定主题风格,可设置”default”、”simple”,指定simple时需要引入simple.css; 默认值: “default”
resizeType: 0,           //2或1或0,2时可以拖动改变宽度和高度,1时只能改变高度,0时不能拖动;默认值: 2
allowFileManager:true,   //true时显示浏览远程服务器按钮 ;默认值: false
allowMediaUpload:false, //true时显示视音频上传按钮。默认值: true
allowFlashUpload:false, //true时显示Flash上传按钮;默认值: true
uploadJson:'${pageContext.request.contextPath}/uploadAction!kindEditorUpload.action',          //指定上传文件的服务器端程序
fileManagerJson:'${pageContext.request.contextPath}/uploadAction!kindEditorView.action',     //指定浏览远程图片的服务器端程序
afterCreate:function(){ //加载完成后改变皮肤
var color = $('.panel-header').css('background-color');
$('.ke-toolbar').css('background-color',color);
}

};
editor = KindEditor.create('#editor_id',options);
/**
*提交表单
*/
$('#kindEditor').click(function(){
var f = $('#kindEditor_From');

f.form({
url : '${pageContext.request.contextPath}/uploadAction!saveData.action',
onSubmit : function() {
editor.sync();
var isValid = $(this).form('validate');
return isValid;
},
success : function(d) {
var json = $.parseJSON(d);
if (json.success) {
$('#editor_name').val("");
editor.html("");
}
$.messager.show({
title : '提示',
msg : json.msg,
});
}
});
f.submit();

});
});
/**
* 浏览服务器文件
*/
function fileManage() {
editor.loadPlugin('filemanager', function() {
editor.plugin.filemanagerDialog({
viewType : 'VIEW',
dirName : 'image',
clickFn : function(url, title) {
editor.insertHtml('<img src="'+url+'" alt="" />');
editor.hideDialog();
}
});
});
}
</script>

<div style="padding:5px;">

<form id="kindEditor_From" method="post">
文章标题:<input name="cname" id=editor_name class="easyui-validatebox" data-options="required:true,missingMessage:'请填写文章标题称'" style="width: 80%;" />
<a  class="easyui-linkbutton" onclick="fileManage();" data-options="iconCls:'icon-search',plain:true" >浏览服务器</a>
<textarea id="editor_id" name="cdesc" style="width:100%;height:400px;">
<strong>HTML内容</strong>
</textarea>
<a id="kindEditor" class="easyui-linkbutton" data-options="iconCls:'icon-ok'" style="position:relative;float:right;margin-top:5px;margin-right:5px">提交</a>
</form>
</div>


后台JAVA上传程序片:

/**
* KindEditor上传文件
*/
public void kindEditorUpload(){
Map<String, Object> m = new HashMap<String, Object>();
m.put("error", 1);
m.put("message", "上传失败!");
String savePath = ServletActionContext.getServletContext().getRealPath("/") + ResourceUtil.getUploadDirectory() + "/";// 文件保存目录路径
String saveUrl = "/" + ResourceUtil.getUploadDirectory() + "/";// 文件保存目录URL

// 定义允许上传的文件扩展名
HashMap<String, String> extMap = new HashMap<String, String>();
extMap.put("image", ResourceUtil.get("image"));
extMap.put("flash", ResourceUtil.get("flash"));
extMap.put("media", ResourceUtil.get("media"));
extMap.put("file", ResourceUtil.get("file"));

// 检查目录
File uploadDir = new File(savePath);
if (!uploadDir.isDirectory()) {
uploadDir.mkdirs();
}

// 检查目录写权限
if (!uploadDir.canWrite()) {
m.put("error", 1);
m.put("message", "上传目录没有写权限!");
super.writeJson(m);
return ;
}

String dirName = ServletActionContext.getRequest().getParameter("dir");
logger.info(dirName);
if (dirName == null) {
dirName = "image";
}
if (!extMap.containsKey(dirName)) {
m.put("error", 1);
m.put("message", "目录名不正确!");
super.writeJson(m);
return ;
}

// 创建文件夹
savePath += dirName + "/";
saveUrl += dirName + "/";
File saveDirFile = new File(savePath);
if (!saveDirFile.exists()) {
saveDirFile.mkdirs();
}
SimpleDateFormat yearDf = new SimpleDateFormat("yyyy");
SimpleDateFormat monthDf = new SimpleDateFormat("MM");
SimpleDateFormat dateDf = new SimpleDateFormat("dd");
Date date = new Date();
String ymd = yearDf.format(date) + "/" + monthDf.format(date) + "/" + dateDf.format(date) + "/";
savePath += ymd;
saveUrl += ymd;
File dirFile = new File(savePath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}

MultiPartRequestWrapper multiPartRequest = (MultiPartRequestWrapper) ServletActionContext.getRequest();// 由于struts2上传文件时自动使用了request封装
File[] files = multiPartRequest.getFiles("imgFile");// 上传的文件集合
String[] fileNames = multiPartRequest.getFileNames("imgFile");// 上传文件名称集合
logger.info(files.length);
if (files == null || files.length < 1) {
m.put("error", 1);
m.put("message", "请选择文件!");
super.writeJson(m);
return ;
}

for (int i = 0; i < files.length; i++) {// 循环所有文件
File file = files[i];// 上传的文件(临时文件)
String fileName = fileNames[i];// 上传文件名

if (file.length() > ResourceUtil.getUploadFileMaxSize()) {
m.put("error", 1);
m.put("message", "上传文件超出限制大小!");
super.writeJson(m);
return ;
}

// 检查扩展名
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if (!Arrays.<String> asList(extMap.get(dirName).split(",")).contains(fileExt)) {
m.put("error", 1);
m.put("message", "上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式!");
super.writeJson(m);
return ;
}

String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;// 新的文件名称
File uploadedFile = new File(savePath, newFileName);

try {
FileCopyUtils.copy(file, uploadedFile);// 利用spring的文件工具上传
m.put("error", 0);
m.put("url", ServletActionContext.getRequest().getContextPath() +saveUrl + newFileName);
super.writeJson(m);
return ;
} catch (Exception e) {
m.put("error", 1);
m.put("message", "上传文件失败");
super.writeJson(m);
}

}

super.writeJson(m);
}


浏览服务器文件程序片:

/**
* 浏览服务器文件
*/
public void kindEditorView(){
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
PrintWriter out =null;
try {
out = response.getWriter();
} catch (IOException e) {
e.printStackTrace();
}

//根目录路径,可以指定绝对路径,比如 /var/www/attached/
String rootPath = ServletActionContext.getServletContext().getRealPath("/") + ResourceUtil.getUploadDirectory() + "/";// 文件保存目录路径
//根目录URL,可以指定绝对路径,比如 http://www.yoursite.com/attached/ String rootUrl =request.getContextPath()+ "/" + ResourceUtil.getUploadDirectory() + "/";// 文件保存目录URL
//图片扩展名
String[] fileTypes = new String[]{"gif", "jpg", "jpeg", "png", "bmp"};

String dirName = request.getParameter("dir");
if (dirName != null) {
if(!Arrays.<String>asList(new String[]{"image", "flash", "media", "file"}).contains(dirName)){
out.println("无效的目录名称!");
return;
}
rootPath += dirName + "/";
rootUrl += dirName + "/";
File saveDirFile = new File(rootPath);
if (!saveDirFile.exists()) {
saveDirFile.mkdirs();
}
}
//根据path参数,设置各路径和URL
String path = request.getParameter("path") != null ? request.getParameter("path") : "";
String currentPath = rootPath + path;
String currentUrl = rootUrl + path;
String currentDirPath = path;
String moveupDirPath = "";
if (!"".equals(path)) {
String str = currentDirPath.substring(0, currentDirPath.length() - 1);
moveupDirPath = str.lastIndexOf("/") >= 0 ? str.substring(0, str.lastIndexOf("/") + 1) : "";
}

//排序形式,name or size or type
String order = request.getParameter("order") != null ? request.getParameter("order").toLowerCase() : "name";

//不允许使用..移动到上一级目录
if (path.indexOf("..") >= 0) {
out.println("不允许访问!");
return;
}
//最后一个字符不是/
if (!"".equals(path) && !path.endsWith("/")) {
out.println("参数无效!");
return;
}
//目录不存在或不是目录
File currentPathFile = new File(currentPath);
if(!currentPathFile.isDirectory()){
out.println("目录不存在!");
return;
}

//遍历目录取的文件信息
List<Hashtable> fileList = new ArrayList<Hashtable>();
if(currentPathFile.listFiles() != null) {
for (File file : currentPathFile.listFiles()) {
Hashtable<String, Object> hash = new Hashtable<String, Object>();
String fileName = file.getName();
if(file.isDirectory()) {
hash.put("is_dir", true);
hash.put("has_file", (file.listFiles() != null));
hash.put("filesize", 0L);
hash.put("is_photo", false);
hash.put("filetype", "");
} else if(file.isFile()){
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
hash.put("is_dir", false);
hash.put("has_file", false);
hash.put("filesize", file.length());
hash.put("is_photo", Arrays.<String>asList(fileTypes).contains(fileExt));
hash.put("filetype", fileExt);
}
hash.put("filename", fileName);
hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));
fileList.add(hash);
}
}

if ("size".equals(order)) {
Collections.sort(fileList, new SizeComparator());
} else if ("type".equals(order)) {
Collections.sort(fileList, new TypeComparator());
} else {
Collections.sort(fileList, new NameComparator());
}
Map<String, Object> result = new HashMap<String, Object>();
result.put("moveup_dir_path", moveupDirPath);
result.put("current_dir_path", currentDirPath);
result.put("current_url", currentUrl);
result.put("total_count", fileList.size());
result.put("file_list", fileList);
super.writeJson(result);
}


浏览服务器文件 用到的三个类:

NameComparator

package zy.comparator;

import java.util.Comparator;
import java.util.Hashtable;

public class NameComparator implements Comparator {
public int compare(Object a, Object b) {
Hashtable hashA = (Hashtable) a;
Hashtable hashB = (Hashtable) b;
if (((Boolean) hashA.get("is_dir")) && !((Boolean) hashB.get("is_dir"))) {
return -1;
} else if (!((Boolean) hashA.get("is_dir")) && ((Boolean) hashB.get("is_dir"))) {
return 1;
} else {
return ((String) hashA.get("filename")).compareTo((String) hashB.get("filename"));
}
}
}


SizeComparator

package zy.comparator;

import java.util.Comparator;
import java.util.Hashtable;

public class SizeComparator implements Comparator {
public int compare(Object a, Object b) {
Hashtable hashA = (Hashtable) a;
Hashtable hashB = (Hashtable) b;
if (((Boolean) hashA.get("is_dir")) && !((Boolean) hashB.get("is_dir"))) {
return -1;
} else if (!((Boolean) hashA.get("is_dir")) && ((Boolean) hashB.get("is_dir"))) {
return 1;
} else {
if (((Long) hashA.get("filesize")) > ((Long) hashB.get("filesize"))) {
return 1;
} else if (((Long) hashA.get("filesize")) < ((Long) hashB.get("filesize"))) {
return -1;
} else {
return 0;
}
}
}
}


TypeComparator

package zy.comparator;

import java.util.Comparator;
import java.util.Hashtable;

public class TypeComparator implements Comparator {
public int compare(Object a, Object b) {
Hashtable hashA = (Hashtable) a;
Hashtable hashB = (Hashtable) b;
if (((Boolean) hashA.get("is_dir")) && !((Boolean) hashB.get("is_dir"))) {
return -1;
} else if (!((Boolean) hashA.get("is_dir")) && ((Boolean) hashB.get("is_dir"))) {
return 1;
} else {
return ((String) hashA.get("filetype")).compareTo((String) hashB.get("filetype"));
}
}
}<SPAN style="COLOR: #ff0000">
</SPAN>


 

说明;

super.writeJson(result);方法是返回JSON;我用的fastjson插件返回json数据

public void writeJson(Object obj){

  String json = JSON.toJSONStringWithDateFormat(obj, "yyyy-MM-dd HH:mm:ss");

  ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");

  try {

   PrintWriter out = ServletActionContext.getResponse().getWriter();

   out.write(json);

   out.flush();

   out.close();

  } catch (IOException e) {

   e.printStackTrace();

  }

 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息