利用commons-fileupload 上传图片(包含表单数据)

在一个表单中包含普通文本数据,另外还有需要上传的图片,那么本程序将图片保存到服务器上的一个图片目录中,文本数据则获取然后输出,查看传输是否正确,后面的处理为涉及。

上传的jsp页面:

需要用到的两个jar包,commons-fileupload-1.2.2.jar  commons-io.jar

jsp页面:

[html] view plain copy
 
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.       
  12.     <title>My JSP 'index.jsp' starting page</title>  
  13.     <meta http-equiv="pragma" content="no-cache">  
  14.     <meta http-equiv="cache-control" content="no-cache">  
  15.     <meta http-equiv="expires" content="0">      
  16.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  17.     <meta http-equiv="description" content="This is my page">  
  18.     <!-- 
  19.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  20.     -->  
  21.   </head>  
  22.     
  23.   <body>  
  24.     <form id="form5" method="post" enctype="multipart/form-data" <strong</strongaction="ReceiveFile" >  
  25.      
  26.     <table class="rounded-corner menu1" id="table_menu5" border="1px solid">  
  27.         <thead align="center">  
  28.             <tr>  
  29.                 <th>显示名称 </th>  
  30.                 <th>链接地址</th>  
  31.             </tr>  
  32.         </thead>  
  33.         <tbody >  
  34.             <tr class="odd" >  
  35.                 <td width="20%" align="center"><input value="中国青少年宫协会" readonly="readonly" name="input_value5" class="menu5_input1"></td>  
  36.                 <td width="50%" align="center"><input value="http://www.cnypa.org/" readonly="readonly" style=" 500px;" name="input_value5"></td>  
  37.             </tr>   
  38.             <tr class="odd" >  
  39.                 <td width="20%" align="center"><input type="file"text" value="浏览" readonly="readonly" name="input_value5" class="menu5_input1"></td>  
  40.                 <td width="50%" align="center"><input value=""  style=" 500px;" name="input_value5"></td>  
  41.             </tr>   
  42.             </tbody>  
  43.         </table>  
  44.   
  45.     <table class="rounded-corner menu1" >  
  46.         <tfoot align="right">  
  47.         <tr>  
  48.         <td></td>  
  49.             <td>  
  50.                 <input type="submit"" value="保存" id="save5"  onclick="check5();">  
  51.             </td>  
  52.         </tr>  
  53.         </tfoot>  
  54.     </table>  
  55.       
  56.       
  57.  </form>  
  58.   </body>  
  59. </html>  


servlet后台程序

[java] view plain copy
 
  1. package dai;  
  2.   
  3.   
  4. import java.io.File;  
  5. import java.io.IOException;  
  6. import java.util.ArrayList;  
  7. import java.util.List;  
  8.   
  9. import javax.servlet.ServletException;  
  10. import javax.servlet.http.HttpServlet;  
  11. import javax.servlet.http.HttpServletRequest;  
  12. import javax.servlet.http.HttpServletResponse;  
  13.   
  14. import org.apache.commons.fileupload.FileItem;  
  15. import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
  16. import org.apache.commons.fileupload.servlet.ServletFileUpload;  
  17.   
  18. public class ReceiveFile extends HttpServlet {  
  19.       
  20.     private String uploadPath = "uploadpic/upload/"; // 上传文件的目录    
  21.     private String tempPath = "uploadpic/uploadtmp/"; // 临时文件目录    
  22.     private String serverPath = null;   
  23.     private String[] fileType = new String[]{".jpg",".gif",".bmp",".png",".jpeg",".ico"};  
  24.     private int sizeMax = 5;//图片最大上限    
  25.       
  26.     @Override  
  27.     protected void doPost(HttpServletRequest request, HttpServletResponse response)  
  28.             throws ServletException, IOException {  
  29.         // 服务器端根目录  
  30.         String serverPath = getServletContext().getRealPath("/").replace("\", "/");    
  31. //        System.out.println(serverPath);  
  32.         //Servlet初始化时执行,如果上传文件目录不存在则自动创建    
  33.         if(!new File(serverPath+uploadPath).isDirectory()){   
  34.             new File(serverPath+uploadPath).mkdirs();    
  35.         }    
  36.         if(!new File(serverPath+tempPath).isDirectory()){  
  37.             new File(serverPath+tempPath).mkdirs();  
  38.         }   
  39.         DiskFileItemFactory factory = new DiskFileItemFactory();  
  40.         factory.setSizeThreshold(5*1024); //最大缓存    
  41.         factory.setRepository(new File(serverPath+tempPath));//临时文件目录    
  42.             
  43.         ServletFileUpload upload = new ServletFileUpload(factory);  
  44.         upload.setSizeMax(sizeMax*1024*1024);//文件最大上限   
  45.             
  46.         String filePath = null;    
  47.         try {    
  48.             List<FileItem> items = upload.parseRequest(request);//获取所有文件列表   
  49.             //  
  50.             for (int i=0;i<items.size();i++) {  
  51.                 //里面一个for循环,获取一行的数据  
  52.                 FileItem item = items.get(i);  
  53. <span style="white-space:pre">  </span>          if(!item.isFormField()){//文件名    
  54.                     String fileName = item.getName().toLowerCase();  
  55.                     if(fileName.endsWith(fileType[0])||fileName.endsWith(fileType[1])||fileName.endsWith(fileType[2])||fileName.endsWith(fileType[3])||fileName.endsWith(fileType[4])||fileName.endsWith(fileType[5])){    
  56. //                        String uuid = UUID.randomUUID().toString();    
  57.                         filePath = serverPath+uploadPath+fileName;  
  58. //                        System.out.println(filePath);  
  59.                         File file = new File(filePath);  
  60.                         item.write(file);  
  61.                         System.out.println(fileName);  
  62.                      }else {  
  63.                         request.setAttribute("errorMsg", "上传失败,请确认上传的文件存在并且类型是图片!");  
  64.                         request.getRequestDispatcher("uploaderror.jsp").forward(request,response);   
  65.                     }  
  66.                 }else {  
  67.                   //非文件流     
  68.                     String value=item.getString();  
  69.                     value = new String(value.getBytes("ISO-8859-1"),"UTF-8");  
  70. //                    System.out.println(value);  
  71.                     System.out.println(value);  
  72.                 }  
  73.                   
  74.             }   
  75.         } catch (Exception e) {  
  76.             e.printStackTrace();    
  77.             request.setAttribute("errorMsg", "上传失败,请确认上传的文件存在并且类型是图片!");  
  78.             request.getRequestDispatcher("uploaderror.jsp").forward(request,response);   
  79.         }  
  80.     }  
  81.       
  82.     @Override  
  83.     protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
  84.             throws ServletException, IOException {  
  85.         this.doPost(req, resp);  
  86.     }  
  87. }  

另外,文章中有几个注意点,像form表单的enctype="multipart/form-data" 需要注意,然后后台处理的时候需要将文件和普通文本数据分开处理,先说的大概,详细的下次再来编辑,源码的话我上传到这里:http://download.csdn.net/detail/xiaobaismiley/6333407

原文地址:https://www.cnblogs.com/meishibiexuejava/p/8405550.html