SpringMVC下的kindeditor实现



本JSP程序是演示程序,建议不要直接在实际项目中使用。
如果您确定直接使用本程序,使用之前请仔细确认相关安全设置。
 
使用方法:


1. 解压zip文件,将所有文件复制到Tomcat的webapps/kindeditor目录下。


2. 将kindeditor/jsp/lib目录下的3个jar文件复制到Tomcat的lib目录下,并重新启动Tomcat。
* commons-fileupload-1.2.1.jar
* commons-io-1.4.jar
* json_simple-1.1.jar
3.将plugin/image/image.js文件中的uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php改为uploadJson = K.undef(self.uploadJson, self.basePath + 'jsp/upload_json.jsp

4. 打开浏览器,输入http://localhost:[P0RT]/kindeditor/jsp/demo.jsp。



这里的绝对路径是指项目以外的某个固定路径,如:d:/attached、e:/xxx/yyy。

使用过KindEditor就会知道,它默认的文件(图片、音视频、flash、file)是上传至项目的跟目录下面, 创建这样一个目录

[java]  view plain copy
  1. String savePath = pageContext.getServletContext().getRealPath("/") + "attached/";  

在这个目录下,再根据文件类型创建不同的子文件夹保存不同类型的文件, 在文件上传以后返回一个对应路径的url供页面显示:默认情况下,如果项目名为:demo,上传一个xxx.txt后,返回前端的url为 demo/attached/20140623/file/xxx.txt;  日期也是个子文件夹,它还会改掉文件名,这个就不细说。

这样一个url在页面的KindEditor编辑框里显示为<a href='demo/attached/2014-06-23/file/xxx.txt'>demo/attached/2014-06-23/file/xxx.txt</a>; 当点击这个连接时,可以直接从项目下面找到这个文件,并显示在浏览器中, 所以支持的文件上传类型也都是可以在浏览器中显示的类型。


这样的实现很明显是不能满足需求的,因为项目重新部属后文件系统就没有了,保存到后台的新闻内容里面的图片,文件链接都会失效!  如果能将文件保存至固定硬盘目录下面则可以解决这个问题!

实现:

首先将默认的upload_json.jsp、file_manager_json.jsp里面的内容移到Controller里面:

[java]  view plain copy
  1. /** 
  2.       * 文件上传 
  3.       * @param request {@link HttpServletRequest} 
  4.       * @param response {@link HttpServletResponse} 
  5.       * @return json response 
  6.       */  
  7.     @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)  
  8.     @ResponseBody  
  9.     public Map<String, Object> fileUpload(HttpServletRequest request, HttpServletResponse response) {  
  10.         //文件保存本地目录路径  
  11.         String savePath = "d:/attached/";  
  12.         //文件保存目录URL  
  13.         String saveUrl = request.getContextPath() + savePath.substring(2);  
  14.   
  15.         if(!ServletFileUpload.isMultipartContent(request)){  
  16.             return getError("请选择文件。");  
  17.         }  
  18.         //检查目录  
  19.         /*File uploadDir = new File(savePath); 
  20.         if(!uploadDir.isDirectory()){ 
  21.             return getError("上传目录不存在。"); 
  22.         } 
  23.         //检查目录写权限 
  24.         if(!uploadDir.canWrite()){ 
  25.             return getError("上传目录没有写权限。"); 
  26.         }*/  
  27.   
  28.         String dirName = request.getParameter("dir");  
  29.         if (dirName == null) {  
  30.             dirName = "image";  
  31.         }  
  32.           
  33.         //定义允许上传的文件扩展名  
  34.         Map<String, String> extMap = new HashMap<String, String>();  
  35.         extMap.put("image""gif,jpg,jpeg,png,bmp");  
  36.         extMap.put("flash""swf,flv");  
  37.         extMap.put("media""swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");  
  38.         extMap.put("file""doc,docx,xls,xlsx,ppt,htm,html,xml,txt,zip,rar,gz,bz2");  
  39.           
  40.         if(!extMap.containsKey(dirName)){  
  41.             return getError("目录名不正确。");  
  42.         }  
  43.         //创建文件夹  
  44.         savePath += dirName + "/";  
  45.         saveUrl += dirName + "/";  
  46.         File saveDirFile = new File(savePath);  
  47.         if (!saveDirFile.exists()) {  
  48.             saveDirFile.mkdirs();  
  49.         }  
  50.           
  51.         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");  
  52.         String ymd = sdf.format(new Date());  
  53.         savePath += ymd + "/";  
  54.         saveUrl += ymd + "/";  
  55.         File dirFile = new File(savePath);  
  56.         if (!dirFile.exists()) {  
  57.             dirFile.mkdirs();  
  58.         }  
  59.           
  60.         //最大文件大小  
  61.         long maxSize = 1000000;  
  62.           
  63.         FileItemFactory factory = new DiskFileItemFactory();  
  64.         ServletFileUpload upload = new ServletFileUpload(factory);  
  65.         upload.setHeaderEncoding("UTF-8");  
  66.         List<?> items = null;  
  67.         try {  
  68.             items = upload.parseRequest(request);  
  69.         } catch (FileUploadException fe) {  
  70.             return getError("接收文件异常。");  
  71.         }  
  72.         Iterator<?> itr = items.iterator();  
  73.         while (itr.hasNext()) {  
  74.             FileItem item = (FileItem) itr.next();  
  75.             String fileName = item.getName();  
  76.             if (!item.isFormField()) {  
  77.                 //检查文件大小  
  78.                 if(item.getSize() > maxSize){  
  79.                     return getError("上传文件大小超过限制。");  
  80.                 }  
  81.                 //检查扩展名  
  82.                 String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();  
  83.                 if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){  
  84.                     return getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。");  
  85.                 }  
  86.   
  87.                 SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");  
  88.                 String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;  
  89.                 try{  
  90.                     File uploadedFile = new File(savePath, newFileName);  
  91.                     item.write(uploadedFile);  
  92.                 }catch(Exception e){  
  93.                     return getError("上传文件失败。");  
  94.                 }  
  95.                   
  96.                 Map<String, Object> succMap = new HashMap<String, Object>();  
  97.                 succMap.put("error"0);  
  98.                 succMap.put("url", saveUrl + newFileName);  
  99.                 return succMap;  
  100.             }  
  101.         }  
  102.           
  103.         return null;  
  104.     }  
  105.   
  106.     private Map<String, Object> getError(String errorMsg) {  
  107.         Map<String, Object> errorMap = new HashMap<String, Object>();  
  108.         errorMap.put("error"1);  
  109.         errorMap.put("message", errorMsg);  
  110.         return errorMap;  
  111.     }  
  112.       
  113.     /** 
  114.       * 文件空间 
  115.       * @param request {@link HttpServletRequest} 
  116.       * @param response {@link HttpServletResponse} 
  117.       * @return json 
  118.       */  
  119.     @RequestMapping(value = "/fileManager")  
  120.     @ResponseBody  
  121.     public Object fileManager(HttpServletRequest request, HttpServletResponse response) {  
  122.         //根目录路径,可以指定绝对路径  
  123.         String rootPath = "d:/attached/";  
  124.         //根目录URL,可以指定绝对路径,比如 http://www.yoursite.com/attached/  
  125.         String rootUrl  = request.getContextPath() + rootPath.substring(2);  
  126.         //图片扩展名  
  127.         String[] fileTypes = new String[]{"gif""jpg""jpeg""png""bmp"};  
  128.   
  129.         String dirName = request.getParameter("dir");  
  130.         if (dirName != null) {  
  131.             if(!Arrays.<String>asList(new String[]{"image""flash""media""file"}).contains(dirName)){  
  132.                 return "Invalid Directory name.";  
  133.             }  
  134.             rootPath += dirName + "/";  
  135.             rootUrl += dirName + "/";  
  136.             File saveDirFile = new File(rootPath);  
  137.             if (!saveDirFile.exists()) {  
  138.                 saveDirFile.mkdirs();  
  139.             }  
  140.         }  
  141.         //根据path参数,设置各路径和URL  
  142.         String path = request.getParameter("path") != null ? request.getParameter("path") : "";  
  143.         String currentPath = rootPath + path;  
  144.         String currentUrl = rootUrl + path;  
  145.         String currentDirPath = path;  
  146.         String moveupDirPath = "";  
  147.         if (!"".equals(path)) {  
  148.             String str = currentDirPath.substring(0, currentDirPath.length() - 1);  
  149.             moveupDirPath = str.lastIndexOf("/") >= 0 ? str.substring(0, str.lastIndexOf("/") + 1) : "";  
  150.         }  
  151.   
  152.         //排序形式,name or size or type  
  153.         String order = request.getParameter("order") != null ? request.getParameter("order").toLowerCase() : "name";  
  154.   
  155.         //不允许使用..移动到上一级目录  
  156.         if (path.indexOf("..") >= 0) {  
  157.             return "Access is not allowed.";  
  158.         }  
  159.         //最后一个字符不是/  
  160.         if (!"".equals(path) && !path.endsWith("/")) {  
  161.             return "Parameter is not valid.";  
  162.         }  
  163.         //目录不存在或不是目录  
  164.         File currentPathFile = new File(currentPath);  
  165.         if(!currentPathFile.isDirectory()){  
  166.             return "Directory does not exist.";  
  167.         }  
  168.   
  169.         //遍历目录取的文件信息  
  170.         List<Map<String, Object>> fileList = new ArrayList<Map<String, Object>>();  
  171.         if(currentPathFile.listFiles() != null) {  
  172.             for (File file : currentPathFile.listFiles()) {  
  173.                 Hashtable<String, Object> hash = new Hashtable<String, Object>();  
  174.                 String fileName = file.getName();  
  175.                 if(file.isDirectory()) {  
  176.                     hash.put("is_dir"true);  
  177.                     hash.put("has_file", (file.listFiles() != null));  
  178.                     hash.put("filesize", 0L);  
  179.                     hash.put("is_photo"false);  
  180.                     hash.put("filetype""");  
  181.                 } else if(file.isFile()){  
  182.                     String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();  
  183.                     hash.put("is_dir"false);  
  184.                     hash.put("has_file"false);  
  185.                     hash.put("filesize", file.length());  
  186.                     hash.put("is_photo", Arrays.<String>asList(fileTypes).contains(fileExt));  
  187.                     hash.put("filetype", fileExt);  
  188.                 }  
  189.                 hash.put("filename", fileName);  
  190.                 hash.put("datetime"new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));  
  191.                 fileList.add(hash);  
  192.             }  
  193.         }  
  194.   
  195.         if ("size".equals(order)) {  
  196.             Collections.sort(fileList, new SizeComparator());  
  197.         } else if ("type".equals(order)) {  
  198.             Collections.sort(fileList, new TypeComparator());  
  199.         } else {  
  200.             Collections.sort(fileList, new NameComparator());  
  201.         }  
  202.         Map<String, Object> result = new HashMap<String, Object>();  
  203.         result.put("moveup_dir_path", moveupDirPath);  
  204.         result.put("current_dir_path", currentDirPath);  
  205.         result.put("current_url", currentUrl);  
  206.         result.put("total_count", fileList.size());  
  207.         result.put("file_list", fileList);  
  208.   
  209.         return result;  
  210.     }  
  211.       
  212.     private class NameComparator implements Comparator<Map<String, Object>> {  
  213.         public int compare(Map<String, Object> hashA, Map<String, Object> hashB) {  
  214.             if (((Boolean)hashA.get("is_dir")) && !((Boolean)hashB.get("is_dir"))) {  
  215.                 return -1;  
  216.             } else if (!((Boolean)hashA.get("is_dir")) && ((Boolean)hashB.get("is_dir"))) {  
  217.                 return 1;  
  218.             } else {  
  219.                 return ((String)hashA.get("filename")).compareTo((String)hashB.get("filename"));  
  220.             }  
  221.         }  
  222.     }  
  223.       
  224.     private class SizeComparator implements Comparator<Map<String, Object>> {  
  225.         public int compare(Map<String, Object> hashA, Map<String, Object> hashB) {  
  226.             if (((Boolean)hashA.get("is_dir")) && !((Boolean)hashB.get("is_dir"))) {  
  227.                 return -1;  
  228.             } else if (!((Boolean)hashA.get("is_dir")) && ((Boolean)hashB.get("is_dir"))) {  
  229.                 return 1;  
  230.             } else {  
  231.                 if (((Long)hashA.get("filesize")) > ((Long)hashB.get("filesize"))) {  
  232.                     return 1;  
  233.                 } else if (((Long)hashA.get("filesize")) < ((Long)hashB.get("filesize"))) {  
  234.                     return -1;  
  235.                 } else {  
  236.                     return 0;  
  237.                 }  
  238.             }  
  239.         }  
  240.     }  
  241.       
  242.     private class TypeComparator implements Comparator<Map<String, Object>> {  
  243.         public int compare(Map<String, Object> hashA, Map<String, Object> hashB) {  
  244.             if (((Boolean)hashA.get("is_dir")) && !((Boolean)hashB.get("is_dir"))) {  
  245.                 return -1;  
  246.             } else if (!((Boolean)hashA.get("is_dir")) && ((Boolean)hashB.get("is_dir"))) {  
  247.                 return 1;  
  248.             } else {  
  249.                 return ((String)hashA.get("filetype")).compareTo((String)hashB.get("filetype"));  
  250.             }  
  251.         }  
  252.     }  

上面的修改较默认的实现只是修改了savePath、saveUrl。

这样同样上传一个xxx.txt后, 文件会被保存到d:/attached/20140623/file/xxx.txt。 返回的url是:demo/attached/20140623/file/xxx.txt。这样到点击a标签将会404,很明显项目下面没有这个attached文件系统。

我们需要用一个Controller来接收所有attached后面的请求,在这个控制层里去d:/attached下面下载指定的文件。


[java]  view plain copy
  1. @Controller  
  2. public class AttachedController {  
  3.       
  4.     private static final Logger LOGGER = Logger.getLogger(AttachedController.class);  
  5.       
  6.     @RequestMapping("/attached/{fileType}/{uploadDate}/{fileName}.{suffix}")  
  7.     public void attached(HttpServletRequest request, HttpServletResponse response,   
  8.             @PathVariable String fileType,  
  9.             @PathVariable String uploadDate,  
  10.             @PathVariable String suffix,  
  11.             @PathVariable String fileName) {  
  12.         //根据suffix设置响应ContentType  
  13.         //response.setContentType("text/html; charset=UTF-8");  
  14.           
  15.         InputStream is = null;  
  16.         OutputStream os = null;  
  17.         try {  
  18.             File file = new File("d:/attached/" + fileType + "/" + uploadDate + "/" + fileName + "." + suffix);  
  19.             is = new FileInputStream(file);  
  20.             byte[] buffer = new byte[is.available()];  
  21.             is.read(buffer);  
  22.               
  23.             os = new BufferedOutputStream(response.getOutputStream());  
  24.             os.write(buffer);  
  25.             os.flush();  
  26.         } catch (Exception e) {  
  27.             //判断suffix  
  28.             //图片请求可以在此显示一个默认图片  
  29.             //file显示文件已损坏等错误提示...  
  30.             LOGGER.error("读取文件失败", e);  
  31.         } finally {  
  32.             if (is != null) {  
  33.                 try {  
  34.                     is.close();  
  35.                 } catch (IOException e) {  
  36.                     LOGGER.error("读取文件失败", e);  
  37.                 }  
  38.                   
  39.                 if (os != null) {  
  40.                     try {  
  41.                         os.close();  
  42.                     } catch (IOException e) {  
  43.                         LOGGER.error("读取文件失败", e);  
  44.                     }  
  45.                 }  
  46.             }  
  47.         }  
  48.           
  49.     }  
  50. }  

这里使用了SpringMVC的@PathVariable功能。

demo/attached/20140623/file/xxx.txt请求, attached方法里,在d盘下找到指定的文件并下载写如response中。

js中配置uploadJson、fileManagerJson(不同版本属性名可能不同我的是4.1.7)这两个属性为Controller拦截的url即可

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值