kinderEditor Struts2整合

环境:

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.   
  132.     public class NameComparator implements Comparator {  
  133.         public int compare(Object a, Object b) {  
  134.             Hashtable hashA = (Hashtable) a;  
  135.             Hashtable hashB = (Hashtable) b;  
  136.             if (((Boolean) hashA.get("is_dir"))  
  137.                     && !((Boolean) hashB.get("is_dir"))) {  
  138.                 return -1;  
  139.             } else if (!((Boolean) hashA.get("is_dir"))  
  140.                     && ((Boolean) hashB.get("is_dir"))) {  
  141.                 return 1;  
  142.             } else {  
  143.                 return ((String) hashA.get("filename"))  
  144.                         .compareTo((String) hashB.get("filename"));  
  145.             }  
  146.         }  
  147.     }  
  148.   
  149.     public class SizeComparator implements Comparator {  
  150.         public int compare(Object a, Object b) {  
  151.             Hashtable hashA = (Hashtable) a;  
  152.             Hashtable hashB = (Hashtable) b;  
  153.             if (((Boolean) hashA.get("is_dir"))  
  154.                     && !((Boolean) hashB.get("is_dir"))) {  
  155.                 return -1;  
  156.             } else if (!((Boolean) hashA.get("is_dir"))  
  157.                     && ((Boolean) hashB.get("is_dir"))) {  
  158.                 return 1;  
  159.             } else {  
  160.                 if (((Long) hashA.get("filesize")) > ((Long) hashB  
  161.                         .get("filesize"))) {  
  162.                     return 1;  
  163.                 } else if (((Long) hashA.get("filesize")) < ((Long) hashB  
  164.                         .get("filesize"))) {  
  165.                     return -1;  
  166.                 } else {  
  167.                     return 0;  
  168.                 }  
  169.             }  
  170.         }  
  171.     }  
  172.   
  173.     public class TypeComparator implements Comparator {  
  174.         public int compare(Object a, Object b) {  
  175.             Hashtable hashA = (Hashtable) a;  
  176.             Hashtable hashB = (Hashtable) b;  
  177.             if (((Boolean) hashA.get("is_dir"))  
  178.                     && !((Boolean) hashB.get("is_dir"))) {  
  179.                 return -1;  
  180.             } else if (!((Boolean) hashA.get("is_dir"))  
  181.                     && ((Boolean) hashB.get("is_dir"))) {  
  182.                 return 1;  
  183.             } else {  
  184.                 return ((String) hashA.get("filetype"))  
  185.                         .compareTo((String) hashB.get("filetype"));  
  186.             }  
  187.         }  
  188.     }  
  189.   
  190.     public String path;  
  191.   
  192.     public String getPath() {  
  193.         return path;  
  194.     }  
  195.   
  196.     public void setPath(String path) {  
  197.         this.path = path;  
  198.     }  
  199.   
  200.       
  201. }  

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.      * 上传的文件类型 
  146.      */  
  147.     public String dir;  
  148.       
  149.     public File imgFile;  
  150.     private String imgFileFileName;  
  151.       
  152.     public String getDir() {  
  153.         return dir;  
  154.     }  
  155.   
  156.     public void setDir(String dir) {  
  157.         this.dir = dir;  
  158.     }  
  159.   
  160.     public File getImgFile() {  
  161.         return imgFile;  
  162.     }  
  163.   
  164.     public void setImgFile(File imgFile) {  
  165.         this.imgFile = imgFile;  
  166.     }  
  167.   
  168.     public String getImgFileFileName() {  
  169.         return imgFileFileName;  
  170.     }  
  171.   
  172.     public void setImgFileFileName(String imgFileFileName) {  
  173.         this.imgFileFileName = imgFileFileName;  
  174.     }  
  175. }  

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

JSP文件调用:

[javascript] view plain copy
  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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SQLAlchemy 是一个 SQL 工具包和对象关系映射(ORM)库,用于 Python 编程语言。它提供了一个高级的 SQL 工具和对象关系映射工具,允许开发者以 Python 类和对象的形式操作数据库,而无需编写大量的 SQL 语句。SQLAlchemy 建立在 DBAPI 之上,支持多种数据库后端,如 SQLite, MySQL, PostgreSQL 等。 SQLAlchemy 的核心功能: 对象关系映射(ORM): SQLAlchemy 允许开发者使用 Python 类来表示数据库表,使用类的实例表示表中的行。 开发者可以定义类之间的关系(如一对多、多对多),SQLAlchemy 会自动处理这些关系在数据库中的映射。 通过 ORM,开发者可以像操作 Python 对象一样操作数据库,这大大简化了数据库操作的复杂性。 表达式语言: SQLAlchemy 提供了一个丰富的 SQL 表达式语言,允许开发者以 Python 表达式的方式编写复杂的 SQL 查询。 表达式语言提供了对 SQL 语句的灵活控制,同时保持了代码的可读性和可维护性。 数据库引擎和连接池: SQLAlchemy 支持多种数据库后端,并且为每种后端提供了对应的数据库引擎。 它还提供了连接池管理功能,以优化数据库连接的创建、使用和释放。 会话管理: SQLAlchemy 使用会话(Session)来管理对象的持久化状态。 会话提供了一个工作单元(unit of work)和身份映射(identity map)的概念,使得对象的状态管理和查询更加高效。 事件系统: SQLAlchemy 提供了一个事件系统,允许开发者在 ORM 的各个生命周期阶段插入自定义的钩子函数。 这使得开发者可以在对象加载、修改、删除等操作时执行额外的逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值