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 }
默認的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 }
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文件夾,可以根據需要修改
