实现文件上传,以及表单提交成功的回调函数

  最近在项目中需要实现图片的上传,并且成功后返回图片上传保存路径,通过查找资料探索研究,实现了项目功能需求,记在这方便自己以后查阅,也为有同样需求的码友分享,功能实现比较简单,如果有好的建议和实现方法,还望多多指教。 

主要将实现一下两个功能: 
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("上传文件扩展名是不允许的扩展名。 只允许"    + 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 
这些可以去网上下载,也可以在附件中下载。

原文地址:https://www.cnblogs.com/telwanggs/p/4865697.html