kindeditor 上传下载文件

Posted code never lies

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了kindeditor 上传下载文件相关的知识,希望对你有一定的参考价值。

jsp代码

 1 <script type="text/javascript" src="${pageContext.request.contextPath}/kindeditor/lang/zh-CN.js"></script>
 2 <script type="text/javascript" src="${pageContext.request.contextPath}/kindeditor/kindeditor-all.js"></script>
 3 <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.js"></script>
 4 <script type="text/javascript">
 5     var options = {
 6        items:[\'insertfile\',\'image\'],
 7         uploadJson:"${pageContext.request.contextPath}/UploadServlet"
 8         //uploadJson:"${pageContext.request.contextPath}/kindeditor/jsp/upload_json.jsp"
 9     //    fileManagerJson : "${pageContext.request.contextPath}/kindeditor/jsp/file_manager_json.jsp",
10     //    allowFileManager : true,
11    //     afterUpload: function(){this.sync();}
12     };
13     
14      KindEditor.ready(function(k) {
15         window.editor = k.create("textarea[name=\'content1\']",options);     
16      });
17 </script>
18 </head>
19 <body>
20     <!-- 使用kindeditor上传文件 -->
21     <div style="text-align:center">
22     <form name="example" method="post" action="#">
23         <textarea name="content1" style="width:700px;height:200px;visibility:visible;">
24         
25         
26         </textarea>
27         <br />
28         <input type="submit" name="button" value="提交内容" /> (提交快捷键: Ctrl + Enter)
29     </form>
30     
31      </textarea> 
32    </div>
33 
34 </body>
35 </html>

UploadServlet

  1 package cn.tele.servlet;
  2 
  3 import java.io.File;
  4 import java.io.IOException;
  5 import java.io.PrintWriter;
  6 import java.text.SimpleDateFormat;
  7 import java.util.Arrays;
  8 import java.util.Date;
  9 import java.util.HashMap;
 10 import java.util.Iterator;
 11 import java.util.List;
 12 import java.util.Random;
 13 
 14 import javax.servlet.ServletException;
 15 import javax.servlet.http.HttpServlet;
 16 import javax.servlet.http.HttpServletRequest;
 17 import javax.servlet.http.HttpServletResponse;
 18 
 19 import org.apache.commons.fileupload.FileItem;
 20 import org.apache.commons.fileupload.FileItemFactory;
 21 import org.apache.commons.fileupload.FileUploadException;
 22 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
 23 import org.apache.commons.fileupload.servlet.ServletFileUpload;
 24 import org.json.simple.JSONObject;
 25 
 26 public class UploadServlet extends HttpServlet {
 27 
 28     public void doGet(HttpServletRequest request, HttpServletResponse response)
 29             throws ServletException, IOException {
 30         response.setContentType("text/html;charset = utf-8");
 31         //文件保存目录路径
 32         String savePath = request.getSession().getServletContext().getRealPath("/") + "WEB-INF/attached/";
 33         PrintWriter out = response.getWriter();
 34         //文件保存目录URL
 35         String saveUrl  = request.getContextPath() + "/WEB-INF/attached/";
 36 
 37         //定义允许上传的文件扩展名
 38         HashMap<String, String> extMap = new HashMap<String, String>();
 39         extMap.put("image", "gif,jpg,jpeg,png,bmp");
 40         extMap.put("flash", "swf,flv");
 41         extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
 42         extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
 43 
 44         //最大文件大小
 45         long maxSize = 1000000000;
 46 
 47         response.setContentType("text/html; charset=UTF-8");
 48 
 49         if(!ServletFileUpload.isMultipartContent(request)){
 50             out.println(getError("请选择文件。"));
 51             return;
 52         }
 53         //检查目录
 54         File uploadDir = new File(savePath);
 55         if(!uploadDir.isDirectory()){
 56             out.println(getError("上传目录不存在。"));
 57             return;
 58         }
 59         //检查目录写权限
 60         if(!uploadDir.canWrite()){
 61             out.println(getError("上传目录没有写权限。"));
 62             return;
 63         }
 64 
 65         //单独使用组件时要传递dirName,参考demo3.jsp
 66         String dirName = request.getParameter("dir");
 67         if (dirName == null) {
 68         //    dirName = "image";
 69         }
 70         System.out.println("dirName--------" + dirName);
 71         if(!extMap.containsKey(dirName)){
 72             out.println(getError("目录名不正确。"));
 73             return;
 74         }
 75         //创建文件夹
 76 //        savePath += dirName + "/";
 77 //        saveUrl += dirName + "/";
 78         File saveDirFile = new File(savePath);
 79         if (!saveDirFile.exists()) {
 80             saveDirFile.mkdirs();
 81         }
 82         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
 83         String ymd = sdf.format(new Date());
 84 //        savePath += ymd + "/";
 85 //        saveUrl += ymd + "/";
 86         File dirFile = new File(savePath);
 87         if (!dirFile.exists()) {
 88             dirFile.mkdirs();
 89         }
 90 
 91         FileItemFactory factory = new DiskFileItemFactory();
 92         ServletFileUpload upload = new ServletFileUpload(factory);
 93         upload.setHeaderEncoding("UTF-8");
 94         List items;
 95         try {
 96             items = upload.parseRequest(request);
 97             Iterator itr = items.iterator();
 98             while (itr.hasNext()) {
 99                 FileItem item = (FileItem) itr.next();
100                 String fileName = item.getName();
101                 String oldFileName = fileName;
102                 long fileSize = item.getSize();
103                 if (!item.isFormField()) {
104                     //检查文件大小
105                     if(item.getSize() > maxSize){
106                         out.println(getError("上传文件大小超过限制。"));
107                         return;
108                     }
109                     //检查扩展名
110                     String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
111                     if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){
112                         out.println(getError("上传文件扩展名是不允许的扩展名。\\n只允许" + extMap.get(dirName) + "格式。"));
113                         return;
114                     }
115 
116                     SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
117                     String newFileName = df.format(new Date()) + new Random().nextInt(1000) + "." + fileExt;
118                     File uploadedFile = new File(savePath, newFileName);
119                     item.write(uploadedFile);
120 
121                     JSONObject obj = new JSONObject();
122                     obj.put("error", 0);
123                 //    obj.put("url", saveUrl + newFileName);
124                     obj.put("url",oldFileName);//回显原文件名
125                     out.println(obj.toJSONString());
126          }
127         }
128       }catch (FileUploadException e1) {
129         // TODO Auto-generated catch block
130         e1.printStackTrace();
131     } catch (Exception e) {
132         // TODO Auto-generated catch block
133         e.printStackTrace();
134     }    
135     }
136 
137     public void doPost(HttpServletRequest request, HttpServletResponse response)
138             throws ServletException, IOException {
139         response.setContentType("text/html;charset = utf-8");
140         doGet(request, response);
141     }
142     
143     private String getError(String message) {
144         JSONObject obj = new JSONObject();
145         obj.put("error", 1);
146         obj.put("message", message);
147         return obj.toJSONString();
148     }
149 
150 }
View Code

默认的uploadJson是一个jsp页面,我把其中的代码拷贝到了UploadServlet中,并进行了一些修改

1.修改文件夹的创建方式,默认的创建方式是/attached/fiile(或者是image等)/今天日期/,只保留/attached/

2.修改了上传文件的回显名称

默认的回显路径是这种,非常难以辨认,想显示原来的上传文件名怎么办?

只需更改返回的json格式的url的值即可

 

这样重新上传回显的文件名是这样的

 

你会发现这样多个/kindeditor(我的项目名),如果想要去除,可以到kindeditor.js中搜索insertfile,注释掉formaturl即可

 

重新上传,回显文件名

ps:如果操作之后没有变化,清理下浏览器缓存即可

 3.关于中文乱码

由于文件名已重新命名,避免文件名重复,所以没有中文编码的问题

测试结果:

至此文件上传已完成,接下来是文件下载

文件下载的思路很简单,在jsp页面显示文件列表,然后io下载即可

ListFileServlet此Servlet用于提供下载列表,将列表显示在jsp页面

 1 package cn.tele.servlet;
 2 
 3 import java.io.File;
 4 import java.io.IOException;
 5 import java.net.URI;
 6 import java.net.URL;
 7 import java.util.ArrayList;
 8 import java.util.HashMap;
 9 import java.util.List;
10 import java.util.Map;
11 
12 import javax.servlet.ServletException;
13 import javax.servlet.http.HttpServlet;
14 import javax.servlet.http.HttpServletRequest;
15 import javax.servlet.http.HttpServletResponse;
16 
17 /**
18  * 显示可供下载的文件列表
19  * @author Administrator
20  *
21  */
22 public class ListFileServlet extends HttpServlet {
23 
24     public void doGet(HttpServletRequest request, HttpServletResponse response)
25             throws ServletException, IOException {
26         response.setContentType("text/html;charset = utf-8");
27         //使用kindeditor上传的文件均被重命名为:yyyyMMddHHssmm+三位随机数的形式,所以文件名不需要编码转换
28         String dirPath = this.getServletContext().getRealPath("/WEB-INF/attached/");
29         Map<String,String> map = new HashMap<String, String>();
30         File dir = new File(dirPath);
31         if(dir.isDirectory()) {
32             File[] files = dir.listFiles();
33             for(File file : files) {
34                 map.put(file.getName(),file.getAbsolutePath());
35             }
36         }
37         request.setAttribute("map",map);
38         request.getRequestDispatcher("/WEB-INF/jsp/listFile.jsp").forward(request, response);
39     }
40 
41     public void doPost(HttpServletRequest request, HttpServletResponse response)
42             throws ServletException, IOException {
43         doGet(request, response);
44     }
45 
46 }
View Code

DownLoadServlet,此Servlet用于提供下载功能,注意千万要设置响应头为content-disposition

注意:此程序没有判断文件是否存在

 1 package cn.tele.servlet;
 2 
 3 import java.io.BufferedInputStream;
 4 import java.io.BufferedOutputStream;
 5 import java.io.File;
 6 import java.io.FileInputStream;
 7 import java.io.IOException;
 8 
 9 import javax.servlet.ServletException;
10 import javax.servlet.ServletOutputStream;
11 import javax.servlet.http.HttpServlet;
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpServletResponse;
14 import javax.swing.filechooser.FileNameExtensionFilter;
15 
16 /**
17  * 文件下载
18  * @author Administrator
19  *
20  */
21 public class DownloadServlet extends HttpServlet {
22 
23     public void doGet(HttpServletRequest request, HttpServletResponse response)
24             throws ServletException, IOException {
25         response.setContentType("text/html;charset = utf-8");
26         String fileName  = request.getParameter("fileName");
27         BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));
28         byte[] buff = new byte[1024];
29         ServletOutputStream outputStream = response.getOutputStream();
30         fileName = fileName.replace("\\\\","_");
31         //设置响应头
32         response.setHeader("content-disposition","attachment;filename="+fileName.substring(fileName.lastIndexOf("_")+1));
33         BufferedOutputStream bos = new BufferedOutputStream(outputStream);
34         int count = 0;
35         while((count=bis.read(buff)) != -1) {
36             bos.write(buff,0,count);
37         }
38         bos.flush();
39         bos.close();
40         bis.close();
41     }
42 
43     public void doPost(HttpServletRequest request, HttpServletResponse response)
44             throws ServletException, IOException {
45         doGet(request, response);
46     }
47 
48 }

 

测试结果:

 上传图片与之想类似,需要注意的是如果使用了默认的upload_json.jsp和file_manager_json.jsp,要根据你的需要修改其中的代码,比如上传的路径尽量放在WEB-INF下,

使用file_manager_json.jsp.浏览图片空间时会生成一个mage文件夹,可以根据需要修改

 

以上是关于kindeditor 上传下载文件的主要内容,如果未能解决你的问题,请参考以下文章

kindeditor上传问题

怎样让KindEditor上传图片使用绝对路径

编辑器kindeditor-4.1.10 自动上传图

KindEditor

kindeditor,kindeditor编辑内容无法保存,并且无法上传图片或者文件

KindEditor 文件上传漏洞验证