實現檔案上傳,以及表單提交成功的回撥函式

NO IMAGE

最近在專案中需要實現圖片的上傳,並且成功後返回圖片上傳儲存路徑,通過查詢資料探索研究,實現了專案功能需求,記在這方便自己以後查閱,也為有同樣需求的碼友分享,功能實現比較簡單,如果有好的建議和實現方法,還望多多指教。

下載地址:http://download.csdn.net/detail/xiaole0313/8984223

主要將實現一下兩個功能:
1、使用commons-fileupload實現檔案的上傳(包括圖片);
2、使用jquery-form.js實現表單提交成功的回撥函式。

頁面設計fileupload.jsp:

Html程式碼  收藏程式碼
  1. <%@ page language=”java” contentType=”text/html; charset=UTF-8″ pageEncoding=”UTF-8″%>  
  2. <!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”>  
  3. <html>  
  4. <head>  
  5. <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>  
  6. <title>檔案上傳</title>  
  7. <script src=”static/js/jquery.min.js” type=”text/javascript”></script>  
  8. <script type=”text/javascript” src=”static/js/jquery-form.js”></script>  
  9. <script type=”text/javascript”>  
  10.     function subimtBtn() {  
  11.         var form = $(“form[name=fileForm]”);  
  12.         var options  = {    
  13.             url:’${pageContext.servletContext.contextPath}/servlet/imageUploadServlet’,    
  14.             type:’post’,    
  15.             success:function(data)    
  16.             {    
  17.                 var jsondata = eval(“(” data “)”);  
  18.                 if(jsondata.error == “0”){  
  19.                     var url = jsondata.url;  
  20.                     alert(url)  
  21.                     $(“#img”).attr(“src”,url);  
  22.                 }else{  
  23.                     var message = jsondata.message;  
  24.                     alert(message);  
  25.                 }  
  26.             }    
  27.         };    
  28.         form.ajaxSubmit(options);  
  29.         //$(“#fileForm”).submit();  
  30.     }  
  31. </script>  
  32. </head>  
  33. <body>  
  34.             <div class=”modal-body”>  
  35.                   
  36.                 <form action=’${pageContext.servletContext.contextPath}/servlet/imageUploadServlet’ enctype=”multipart/form-data” method=”post” id=”fileForm” name=”fileForm”>  
  37.                     <input type=”file” name=”filename”>  
  38.                 </form>  
  39.                   
  40.             </div>  
  41.   
  42.             <div class=”modal-footer”>  
  43.                 <button class=”btn btn-primary”  onclick=”subimtBtn();”>提交</button>  
  44.             </div>  
  45.   
  46.     <div>  
  47.      <img alt=”img” src=”” id=”img”>  
  48.     </div>  
  49. </body>  
  50. </html>  

servlet實現:imageUploadServlet.java

Java程式碼  收藏程式碼
  1. package com.system.comtrol;  
  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. import javax.servlet.ServletException;  
  14. import javax.servlet.annotation.WebServlet;  
  15. import javax.servlet.http.HttpServlet;  
  16. import javax.servlet.http.HttpServletRequest;  
  17. import javax.servlet.http.HttpServletResponse;  
  18. import net.sf.json.JSONObject;  
  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.   
  25.   
  26. /** 
  27.  * Servlet implementation class ImageUploadServlet 
  28.  */  
  29. @WebServlet(“/servlet/imageUploadServlet”)  
  30. public class ImageUploadServlet extends HttpServlet {  
  31.     private static final long serialVersionUID = 1L;  
  32.   
  33.     /** 
  34.      * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse 
  35.      *      response) 
  36.      */  
  37.     protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  38.         try {  
  39.             PrintWriter out = response.getWriter();  
  40.             // 檔案儲存目錄路徑  
  41.             String savePath = request.getServletContext().getRealPath(“/”)  “attached”;  
  42.             // 檔案儲存目錄URL  
  43.             String saveUrl = request.getContextPath()   “/attached”;  
  44.             // 定義允許上傳的副檔名  
  45.             HashMap<String, String> extMap = new HashMap<String, String>();  
  46.             extMap.put(“image”, “gif,jpg,jpeg,png,bmp”);  
  47.             // 最大檔案大小  
  48.             long maxSize = 1000000;  
  49.             response.setContentType(“text/html; charset=UTF-8”);  
  50.   
  51.             if (!ServletFileUpload.isMultipartContent(request)) {  
  52.                 out.println(getError(“請選擇檔案。”));  
  53.                 return;  
  54.             }  
  55.             // 檢查目錄  
  56.             File uploadDir = new File(savePath);  
  57.             if (!uploadDir.isDirectory()) {  
  58.                 out.println(getError(“上傳目錄不存在。”));  
  59.                 return;  
  60.             }  
  61.             // 檢查目錄寫許可權  
  62.             if (!uploadDir.canWrite()) {  
  63.                 out.println(getError(“上傳目錄沒有寫許可權。”));  
  64.                 return;  
  65.             }  
  66.   
  67.             String dirName = request.getParameter(“dir”);  
  68.             if (dirName == null) {  
  69.                 dirName = “image”;  
  70.             }  
  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 = upload.parseRequest(request);  
  95.             Iterator itr = items.iterator();  
  96.             while (itr.hasNext()) {  
  97.                 FileItem item = (FileItem) itr.next();  
  98.                 String fileName = item.getName();  
  99.                 if (!item.isFormField()) {  
  100.                     // 檢查檔案大小  
  101.                     if (item.getSize() > maxSize) {  
  102.                         out.println(getError(“上傳檔案大小超過限制。”));  
  103.                         return;  
  104.                     }  
  105.                     // 檢查副檔名  
  106.                     String fileExt = fileName.substring(fileName.lastIndexOf(“.”)   1).toLowerCase();  
  107.                     if (!Arrays.<String> asList(extMap.get(dirName).split(“,”)).contains(fileExt)) {  
  108.                         out.println(getError(“上傳副檔名是不允許的副檔名。\n只允許”      extMap.get(dirName)   “格式。”));  
  109.                         return;  
  110.                     }  
  111.   
  112.                     SimpleDateFormat df = new SimpleDateFormat(“yyyyMMddHHmmss”);  
  113.                     String newFileName = df.format(new Date())   “_”   new Random().nextInt(1000)   “.”   fileExt;  
  114.                     try {  
  115.                         File uploadedFile = new File(savePath, newFileName);  
  116.                         item.write(uploadedFile);  
  117.                     } catch (Exception e) {  
  118.                         out.println(getError(“上傳檔案失敗。”));  
  119.                         return;  
  120.                     }  
  121.   
  122.                     JSONObject obj = new JSONObject();  
  123.                     obj.put(“error”, 0);  
  124.                     obj.put(“url”, saveUrl   newFileName);  
  125.                     out.println(obj.toString());  
  126.                 }  
  127.             }  
  128.         } catch (FileUploadException e1) {  
  129.             e1.printStackTrace();  
  130.         }  
  131.   
  132.     }  
  133.   
  134.     private String getError(String message) {  
  135.         JSONObject obj = new JSONObject();  
  136.         obj.put(“error”, 1);  
  137.         obj.put(“message”, message);  
  138.         return obj.toString();  
  139.     }  
  140.   
  141. }  

專案中依賴的主要jar:commons-fileupload-1.2.jar,commons-io-1.4.jar

主要的兩個js檔案:jquery.min.js,jquery-form.js

下載地址:http://download.csdn.net/detail/xiaole0313/8984223