环境:

kinderEditor4.1.5

Struts2.3.5

Spring3.0.5

Hibernate3.6

代码:

FileManageAction

  1. package com.hcsoft.plugin.editor;
  2.  
  3. import java.io.File;
  4. import java.io.PrintWriter;
  5. import java.text.SimpleDateFormat;
  6. import java.util.ArrayList;
  7. import java.util.Arrays;
  8. import java.util.Collections;
  9. import java.util.Comparator;
  10. import java.util.Hashtable;
  11. import java.util.List;
  12.  
  13. import javax.servlet.http.HttpServletRequest;
  14. import javax.servlet.http.HttpServletResponse;
  15.  
  16. import org.json.simple.JSONObject;
  17.  
  18. import com.hcsoft.action.BaseAction;
  19.  
  20. @SuppressWarnings({"serial", "unchecked", "rawtypes" })
  21. public class FileManageAction extends BaseAction {
  22.  
  23. public String execute() throws Exception {
  24. // 请求
  25. HttpServletRequest request = contextPvd.getRequest();
  26.  
  27. // 根目录路径,可以指定绝对路径,比如 /var/www/attached/
  28. String rootPath = contextPvd.getAppRealPath("/") + "editor/attached/";
  29. // 根目录URL,可以指定绝对路径,比如 http://www.yoursite.com/attached/
  30. String rootUrl = request.getContextPath() + "/editor/attached/";
  31. // 图片扩展名
  32. String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp" };
  33.  
  34. String dirName = request.getParameter("dir");
  35. if (dirName != null) {
  36. if (!Arrays.<String> asList(
  37. new String[] { "image", "flash", "media", "file" })
  38. .contains(dirName)) {
  39. log.error("Invalid Directory name.");
  40. }
  41. rootPath += dirName + "/";
  42. rootUrl += dirName + "/";
  43. File saveDirFile = new File(rootPath);
  44. if (!saveDirFile.exists()) {
  45. saveDirFile.mkdirs();
  46. }
  47. }
  48. // 根据path参数,设置各路径和URL
  49. String currentPath = rootPath + path;
  50. String currentUrl = rootUrl + path;
  51. String currentDirPath = path;
  52. String moveupDirPath = "";
  53. if (!"".equals(path)) {
  54. String str = currentDirPath.substring(0,
  55. currentDirPath.length() - 1);
  56. moveupDirPath = str.lastIndexOf("/") >= 0 ? str.substring(0,
  57. str.lastIndexOf("/") + 1) : "";
  58. }
  59.  
  60. // 排序形式,name or size or type
  61. String order = request.getParameter("order") != null ? request
  62. .getParameter("order").toLowerCase() : "name";
  63.  
  64. // 不允许使用..移动到上一级目录
  65. if (path.indexOf("..") >= 0) {
  66. log.error("Access is not allowed.");
  67. }
  68. // 最后一个字符不是/
  69. if (!"".equals(path) && !path.endsWith("/")) {
  70. log.error("Parameter is not valid.");
  71. }
  72. // 目录不存在或不是目录
  73. File currentPathFile = new File(currentPath);
  74. if (!currentPathFile.isDirectory()) {
  75. log.error("Directory does not exist.");
  76. }
  77.  
  78. // 遍历目录取的文件信息
  79. List<Hashtable> fileList = new ArrayList<Hashtable>();
  80. if (currentPathFile.listFiles() != null) {
  81. for (File file : currentPathFile.listFiles()) {
  82. Hashtable<String, Object> hash = new Hashtable<String, Object>();
  83. String fileName = file.getName();
  84. if (file.isDirectory()) {
  85. hash.put("is_dir", true);
  86. hash.put("has_file", (file.listFiles() != null));
  87. hash.put("filesize", 0L);
  88. hash.put("is_photo", false);
  89. hash.put("filetype", "");
  90. } else if (file.isFile()) {
  91. String fileExt = fileName.substring(
  92. fileName.lastIndexOf(".") + 1).toLowerCase();
  93. hash.put("is_dir", false);
  94. hash.put("has_file", false);
  95. hash.put("filesize", file.length());
  96. hash.put("is_photo", Arrays.<String> asList(fileTypes)
  97. .contains(fileExt));
  98. hash.put("filetype", fileExt);
  99. }
  100. hash.put("filename", fileName);
  101. hash.put("datetime",
  102. new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file
  103. .lastModified()));
  104. fileList.add(hash);
  105. }
  106. }
  107.  
  108. if ("size".equals(order)) {
  109. Collections.sort(fileList, new SizeComparator());
  110. } else if ("type".equals(order)) {
  111. Collections.sort(fileList, new TypeComparator());
  112. } else {
  113. Collections.sort(fileList, new NameComparator());
  114. }
  115.  
  116. //响应
  117. HttpServletResponse response = contextPvd.getResponse();
  118. response.setContentType("application/json; charset=UTF-8");
  119. PrintWriter out = response.getWriter();
  120.  
  121. JSONObject obj = new JSONObject();
  122. obj.put("moveup_dir_path", moveupDirPath);
  123. obj.put("current_dir_path", currentDirPath);
  124. obj.put("current_url", currentUrl);
  125. obj.put("total_count", fileList.size());
  126. obj.put("file_list", fileList);
  127. out.println(obj.toJSONString());
  128. return null;
  129. }
  130.  
  131. public class NameComparator implements Comparator {
  132. public int compare(Object a, Object b) {
  133. Hashtable hashA = (Hashtable) a;
  134. Hashtable hashB = (Hashtable) b;
  135. if (((Boolean) hashA.get("is_dir"))
  136. && !((Boolean) hashB.get("is_dir"))) {
  137. return -1;
  138. } else if (!((Boolean) hashA.get("is_dir"))
  139. && ((Boolean) hashB.get("is_dir"))) {
  140. return 1;
  141. } else {
  142. return ((String) hashA.get("filename"))
  143. .compareTo((String) hashB.get("filename"));
  144. }
  145. }
  146. }
  147.  
  148. public class SizeComparator implements Comparator {
  149. public int compare(Object a, Object b) {
  150. Hashtable hashA = (Hashtable) a;
  151. Hashtable hashB = (Hashtable) b;
  152. if (((Boolean) hashA.get("is_dir"))
  153. && !((Boolean) hashB.get("is_dir"))) {
  154. return -1;
  155. } else if (!((Boolean) hashA.get("is_dir"))
  156. && ((Boolean) hashB.get("is_dir"))) {
  157. return 1;
  158. } else {
  159. if (((Long) hashA.get("filesize")) > ((Long) hashB
  160. .get("filesize"))) {
  161. return 1;
  162. } else if (((Long) hashA.get("filesize")) < ((Long) hashB
  163. .get("filesize"))) {
  164. return -1;
  165. } else {
  166. return 0;
  167. }
  168. }
  169. }
  170. }
  171.  
  172. public class TypeComparator implements Comparator {
  173. public int compare(Object a, Object b) {
  174. Hashtable hashA = (Hashtable) a;
  175. Hashtable hashB = (Hashtable) b;
  176. if (((Boolean) hashA.get("is_dir"))
  177. && !((Boolean) hashB.get("is_dir"))) {
  178. return -1;
  179. } else if (!((Boolean) hashA.get("is_dir"))
  180. && ((Boolean) hashB.get("is_dir"))) {
  181. return 1;
  182. } else {
  183. return ((String) hashA.get("filetype"))
  184. .compareTo((String) hashB.get("filetype"));
  185. }
  186. }
  187. }
  188.  
  189. public String path;
  190.  
  191. public String getPath() {
  192. return path;
  193. }
  194.  
  195. public void setPath(String path) {
  196. this.path = path;
  197. }
  198. }

FileUploadAction

  1. package com.hcsoft.plugin.editor;
  2.  
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileOutputStream;
  6. import java.io.InputStream;
  7. import java.io.PrintWriter;
  8. import java.text.SimpleDateFormat;
  9. import java.util.Arrays;
  10. import java.util.Date;
  11. import java.util.HashMap;
  12. import java.util.Random;
  13.  
  14. import javax.servlet.http.HttpServletRequest;
  15. import javax.servlet.http.HttpServletResponse;
  16.  
  17. import org.apache.commons.fileupload.servlet.ServletFileUpload;
  18. import org.json.simple.JSONObject;
  19.  
  20. import com.hcsoft.action.BaseAction;
  21.  
  22. @SuppressWarnings("serial")
  23. public class FileUploadAction extends BaseAction{
  24.  
  25. public String execute() throws Exception {
  26. //响应
  27. HttpServletResponse response = contextPvd.getResponse();
  28. response.setContentType("text/html; charset=UTF-8");
  29. PrintWriter out = response.getWriter();
  30.  
  31. //请求
  32. HttpServletRequest request = contextPvd.getRequest();
  33.  
  34. //文件保存目录路径
  35. String savePath = contextPvd.getAppRealPath("/") + "editor/attached/";
  36.  
  37. //文件保存目录URL
  38. String saveUrl = request.getContextPath() + "/editor/attached/";
  39.  
  40. //定义允许上传的文件扩展名
  41. HashMap<String, String> extMap = new HashMap<String, String>();
  42. extMap.put("image", "gif,jpg,jpeg,png,bmp");
  43. extMap.put("flash", "swf,flv");
  44. extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
  45. extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
  46.  
  47. //最大文件大小
  48. long maxSize = 1000000;
  49.  
  50. if(!ServletFileUpload.isMultipartContent(request)){
  51. return error(out,"请选择文件。");
  52. }
  53. //检查目录
  54. File uploadDir = new File(savePath);
  55. if(!uploadDir.isDirectory()){
  56. return error(out,"上传目录不存在。");
  57. }
  58. //检查目录写权限
  59. if(!uploadDir.canWrite()){
  60. return error(out,"上传目录没有写权限。");
  61. }
  62.  
  63. String dirName = dir;
  64. if (dirName == null) {
  65. dirName = "image";
  66. }
  67. if(!extMap.containsKey(dirName)){
  68. return error(out,"目录名不正确。");
  69. }
  70. //创建文件夹
  71. savePath += dirName + "/";
  72. saveUrl += dirName + "/";
  73. File saveDirFile = new File(savePath);
  74. if (!saveDirFile.exists()) {
  75. saveDirFile.mkdirs();
  76. }
  77. SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
  78. String ymd = sdf.format(new Date());
  79. savePath += ymd + "/";
  80. saveUrl += ymd + "/";
  81. File dirFile = new File(savePath);
  82. if (!dirFile.exists()) {
  83. dirFile.mkdirs();
  84. }
  85.  
  86. if(imgFile != null && !imgFile.toString().equals("")){
  87. long fileSize = imgFile.length();
  88. if(fileSize > maxSize){
  89. return error(out,"上传文件大小超过限制。");
  90. }
  91. //检查扩展名
  92. String fileExt = imgFileFileName.substring(imgFileFileName.lastIndexOf(".") + 1).toLowerCase();
  93. if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){
  94. return error(out,"上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。");
  95. }
  96.  
  97. SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
  98. String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
  99.  
  100. File uploadedFile = new File(savePath, newFileName);
  101. //获取文件输出流
  102. FileOutputStream fos = new FileOutputStream(uploadedFile);
  103. //获取内存中当前文件输入流
  104. InputStream in = new FileInputStream(imgFile);
  105. byte[] buffer = new byte[1024];
  106. try {
  107. int num = 0;
  108. while ((num = in.read(buffer)) > 0) {
  109. fos.write(buffer, 0, num);
  110. }
  111. } catch (Exception e) {
  112. log.error("kindEditor上传文件出错了!");
  113. return error(out,"上传的文件不存在!");
  114. } finally {
  115. in.close();
  116. fos.close();
  117. }
  118. return success(out,saveUrl + newFileName);
  119. }else{
  120. return error(out,"上传的文件不存在!");
  121. }
  122. }
  123.  
  124. @SuppressWarnings("unchecked")
  125. private String error(PrintWriter out,String message){
  126. JSONObject obj = new JSONObject();
  127. obj.put("error", 1);
  128. obj.put("message", message);
  129. out.println(obj.toJSONString());
  130. return null;
  131. }
  132.  
  133. @SuppressWarnings("unchecked")
  134. private String success(PrintWriter out,String url){
  135. JSONObject obj = new JSONObject();
  136. obj.put("error", 0);
  137. obj.put("url", url);
  138. out.println(obj.toJSONString());
  139. return null;
  140. }
  141.  
  142. /**
  143. * 上传的文件类型
  144. */
  145. public String dir;
  146.  
  147. public File imgFile;
  148. private String imgFileFileName;
  149.  
  150. public String getDir() {
  151. return dir;
  152. }
  153.  
  154. public void setDir(String dir) {
  155. this.dir = dir;
  156. }
  157.  
  158. public File getImgFile() {
  159. return imgFile;
  160. }
  161.  
  162. public void setImgFile(File imgFile) {
  163. this.imgFile = imgFile;
  164. }
  165.  
  166. public String getImgFileFileName() {
  167. return imgFileFileName;
  168. }
  169.  
  170. public void setImgFileFileName(String imgFileFileName) {
  171. this.imgFileFileName = imgFileFileName;
  172. }
  173. }

xml配置

  1. <!-- 文件管理 -->
  2. <action name="fileManage" class="fileManageAction"/>
  3. <!-- 文件上传 -->
  4. <action name="fileUpload" class="fileUploadAction" />

JSP文件调用:

  1. KindEditor.ready(function(K) {
  2. editor = K.create('#kindeditor', {
  3. uploadJson : '/manage/fileUpload.do',
  4. fileManagerJson : '/manage/fileManage.do',
  5. allowFileManager : true
  6. });
  1. <s:textarea id="kindeditor" theme="simple" name="entity.description" cssStyle="width:700px;height:300px"/>

本文转自:http://blog.csdn.net/mylovedeye/article/details/9986325

kinderEditor + Struts2整合的更多相关文章

  1. Spring与Struts2整合VS Spring与Spring MVC整合

    Spring与Struts2整合,struts.xml在src目录下 1.在web.xml配置监听器 web.xml <!-- 配置Spring的用于初始化ApplicationContext的 ...

  2. struts2整合spring的思路

    struts2整合spring有有两种策略: >sping容器负责管理控制器Action,并利用依赖注入为控制器注入业务逻辑组件. >利用spring的自动装配,Action将自动会从Sp ...

  3. struts2整合spring出现的Unable to instantiate Action异常

    在struts2整合spring的时候,完全一步步按照官方文档上去做的,最后发现出现 Unable to instantiate Action,网上一搜发现很多人和我一样的问题,配置什么都没有错误,就 ...

  4. struts2整合json要注意的问题

    昨天struts2整合json,一直出错: There is no Action mapped for namespace / and action name ... HTTP Status 404 ...

  5. struts2整合spring应用实例

    我们知道struts1与spring整合是靠org.springframework.web.struts.DelegatingActionProxy来实现的,以下通过具体一个用户登录实现来说明stru ...

  6. struts2整合JFreechart 饼图、折线图、柱形图

    struts2整合JFreechart 饼图.折线图.柱形图 上效果图: 当然可以将数据导出图片格式存储.具体下的链接里的文件有保存成图片的操作. 因为是strust2整合JFreechart,所以s ...

  7. Spring4笔记12--SSH整合3--Spring与Struts2整合

    SSH 框架整合技术: 3. Spring与Struts2整合(对比SpringWeb): Spring 与 Struts2 整合的目的有两个: (1)在 Struts2 的 Action 中,即 V ...

  8. Spring Struts2 整合

    Spring整合Struts2 整合什么?——用IoC容器管理Struts2的Action如何整合?第一步:配置Struts21.加入Struts2的jar包.2.配置web.xml文件.3.加入St ...

  9. Struts2—整合Spring

    Struts2—整合Spring Spring框架是一个非常优秀的轻量级java EE容器,大部分javaEE应用,都会考虑使用Spring容器来管理应用中的组件. Struts2是一个MVC框架,是 ...

随机推荐

  1. phpcms_v9 多图字段 内容页,首页,分页自定义字段调用

    phpcms_v9 多图字段 内容页,首页,分页自定义字段调用 说明:自定义多图字段名 shigongtu 1 内容页调用 {loop $shigongtu $r}      <img src= ...

  2. hdu 5294 最短路+最大流 ***

    处理处最短路径图,这个比较巧妙 链接:点我

  3. Java Security: Illegal key size or default parameters?

    来自:http://stackoverflow.com/questions/6481627/java-security-illegal-key-size-or-default-parameters I ...

  4. 如何在java程序中调用linux命令或者shell脚本

    转自:http://blog.sina.com.cn/s/blog_6433391301019bpn.html 在java程序中如何调用linux的命令?如何调用shell脚本呢? 这里不得不提到ja ...

  5. 求数组的长度 C

    对于数组array,计算其占用内存大小和元素个数的方法如下: C/C++ code ? 1 2 3 4 5 //计算占用内存大小 sizeof(array)   //计算数组元素个数 sizeof(a ...

  6. VC 快速创建多层文件夹

    BOOL CreateDirectory( LPCTSTR lpPathName, LPSECURITY_ATTRIBUTES lpSecurityAttributes ); 这个是大多数用户都知道的 ...

  7. 原生JavaScript 全特效微博发布面板效果实现

    javaScript实现微博发布面板效果.---转载白超华 采用的js知识有: 正则表达式区分中英文字节.随机数生成等函数 淡入淡出.缓冲运动.闪动等动画函数 onfocus.onblur.oninp ...

  8. JVM性能监控工具-Jvisualvm

    用法:Jvisualvm是JDK自带的一款性能分析工具 使用方式: 1.配置好JDK环境变量 1.本地JVM监控略 2.远程JVM监控 用JMX对Resin内存状态进行监控 ,可以看到本地所有可监控的 ...

  9. 通过maven下载jar包

    准备 你得先安装Maven如果不会点击后面的连接查看一二步.http://www.cnblogs.com/luoruiyuan/p/5776558.html 1.在任意目录下创建一个文件夹,其下创建一 ...

  10. TestNg依赖详解(三)------灵活的文件配置依赖

    配置型的依赖测试,让依赖测试不局限于测试代码中,在XML文件中进行灵活的依赖配置 原创文章,版权所有,允许转载,标明出处:http://blog.csdn.net/wanghantong Javaco ...