Servlet實現文件上傳,可多文件上傳

1、Servlet實現文件上傳,須要添加第三方提供的jar包css

接着把這兩個jar包放到 lib文件夾下:html

 

二:java

文件上傳的表單提交方式必須是POST方式,web

編碼類型:enctype="multipart/form-data",默認是 application/x-www-form-urlencodedapache

好比:<form action="FileUpLoad"enctype="multipart/form-data"method="post">數組

 

3、舉例:緩存

1.fileupload.jspapp

 

[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 'fileupload.jsp' starting page</title>  
  13.       
  14.     <meta http-equiv="pragma" content="no-cache">  
  15.     <meta http-equiv="cache-control" content="no-cache">  
  16.     <meta http-equiv="expires" content="0">      
  17.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  18.     <meta http-equiv="description" content="This is my page">  
  19.     <!-- 
  20.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  21.     -->  
  22.   
  23.   </head>  
  24.     
  25.   <body>  
  26.      <!-- enctype 默認是 application/x-www-form-urlencoded -->  
  27.      <form action="FileUpLoad" enctype="multipart/form-data" method="post" >  
  28.           
  29.                用戶名:<input type="text" name="usename"<br/>  
  30.                上傳文件:<input type="file" name="file1"><br/>  
  31.               上傳文件: <input type="file" name="file2"><br/>  
  32.               <input type="submit" value="提交"/>  
  33.        
  34.      </form>  
  35.        
  36.        
  37.        
  38.   </body>  
  39. </html>  


2.實際處理文件上傳的 FileUpLoad.javajsp

 

 

[java]  view plain copy
  1. package com.servlet.fileupload;  
  2.   
  3. import java.io.File;  
  4. import java.io.*;  
  5. import java.io.IOException;  
  6. import java.io.PrintWriter;  
  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.FileUploadException;  
  16. import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
  17. import org.apache.commons.fileupload.servlet.ServletFileUpload;  
  18.   
  19. /** 
  20.  *  
  21.  * @author Administrator 
  22.  * 文件上傳 
  23.  * 具體步驟: 
  24.  * 1)得到磁盤文件條目工廠 DiskFileItemFactory 要導包 
  25.  * 2) 利用 request 獲取 真實路徑 ,供臨時文件存儲,和 最終文件存儲 ,這兩個存儲位置可不一樣,也可相同 
  26.  * 3)對 DiskFileItemFactory 對象設置一些 屬性 
  27.  * 4)高水平的API文件上傳處理  ServletFileUpload upload = new ServletFileUpload(factory); 
  28.  * 目的是調用 parseRequest(request)方法  得到 FileItem 集合list , 
  29.  *      
  30.  * 5)在 FileItem 對象中 獲取信息,   遍歷, 判斷 表單提交過來的信息 是不是 普通文本信息  另作處理 
  31.  * 6) 
  32.  *    第一種. 用第三方 提供的  item.write( new File(path,filename) );  直接寫到磁盤上 
  33.  *    第二種. 手動處理   
  34.  * 
  35.  */  
  36. public class FileUpLoad extends HttpServlet {  
  37.   
  38.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  39.             throws ServletException, IOException {  
  40.           
  41.         request.setCharacterEncoding("utf-8");  //設置編碼  
  42.           
  43.         //得到磁盤文件條目工廠  
  44.         DiskFileItemFactory factory = new DiskFileItemFactory();  
  45.         //獲取文件須要上傳到的路徑  
  46.         String path = request.getRealPath("/upload");  
  47.           
  48.         //若是沒如下兩行設置的話,上傳大的 文件 會佔用 不少內存,  
  49.         //設置暫時存放的 存儲室 , 這個存儲室,能夠和 最終存儲文件 的目錄不一樣  
  50.         /** 
  51.          * 原理 它是先存到 暫時存儲室,而後在真正寫到 對應目錄的硬盤上,  
  52.          * 按理來講 當上傳一個文件時,實際上是上傳了兩份,第一個是以 .tem 格式的  
  53.          * 而後再將其真正寫到 對應目錄的硬盤上 
  54.          */  
  55.         factory.setRepository(new File(path));  
  56.         //設置 緩存的大小,當上傳文件的容量超過該緩存時,直接放到 暫時存儲室  
  57.         factory.setSizeThreshold(1024*1024) ;  
  58.           
  59.         //高水平的API文件上傳處理  
  60.         ServletFileUpload upload = new ServletFileUpload(factory);  
  61.           
  62.           
  63.         try {  
  64.             //能夠上傳多個文件  
  65.             List<FileItem> list = (List<FileItem>)upload.parseRequest(request);  
  66.               
  67.             for(FileItem item : list)  
  68.             {  
  69.                 //獲取表單的屬性名字  
  70.                 String name = item.getFieldName();  
  71.                   
  72.                 //若是獲取的 表單信息是普通的 文本 信息  
  73.                 if(item.isFormField())  
  74.                 {                     
  75.                     //獲取用戶具體輸入的字符串 ,名字起得挺好,由於表單提交過來的是 字符串類型的  
  76.                     String value = item.getString() ;  
  77.                       
  78.                     request.setAttribute(name, value);  
  79.                 }  
  80.                 //對傳入的非 簡單的字符串進行處理 ,好比說二進制的 圖片,電影這些  
  81.                 else  
  82.                 {  
  83.                     /** 
  84.                      * 如下三步,主要獲取 上傳文件的名字 
  85.                      */  
  86.                     //獲取路徑名  
  87.                     String value = item.getName() ;  
  88.                     //索引到最後一個反斜槓  
  89.                     int start = value.lastIndexOf("\\");  
  90.                     //截取 上傳文件的 字符串名字,加1是 去掉反斜槓,  
  91.                     String filename = value.substring(start+1);  
  92.                       
  93.                     request.setAttribute(name, filename);  
  94.                       
  95.                     //真正寫到磁盤上  
  96.                     //它拋出的異常 用exception 捕捉  
  97.                       
  98.                     //item.write( new File(path,filename) );//第三方提供的  
  99.                       
  100.                     //手動寫的  
  101.                     OutputStream out = new FileOutputStream(new File(path,filename));  
  102.                       
  103.                     InputStream in = item.getInputStream() ;  
  104.                       
  105.                     int length = 0 ;  
  106.                     byte [] buf = new byte[1024] ;  
  107.                       
  108.                     System.out.println("獲取上傳文件的總共的容量:"+item.getSize());  
  109.   
  110.                     // in.read(buf) 每次讀到的數據存放在   buf 數組中  
  111.                     while( (length = in.read(buf) ) != -1)  
  112.                     {  
  113.                         //在   buf 數組中 取出數據 寫到 (輸出流)磁盤上  
  114.                         out.write(buf, 0, length);  
  115.                           
  116.                     }  
  117.                       
  118.                     in.close();  
  119.                     out.close();  
  120.                 }  
  121.             }  
  122.               
  123.               
  124.               
  125.         } catch (FileUploadException e) {  
  126.             // TODO Auto-generated catch block  
  127.             e.printStackTrace();  
  128.         }  
  129.         catch (Exception e) {  
  130.             // TODO Auto-generated catch block  
  131.               
  132.             //e.printStackTrace();  
  133.         }  
  134.           
  135.           
  136.         request.getRequestDispatcher("filedemo.jsp").forward(request, response);  
  137.           
  138.   
  139.     }  
  140.   
  141. }  

 

System.out.println("獲取上傳文件的總共的容量:"+item.getSize());  oop

 

3.filedemo.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 'filedemo.jsp' starting page</title>  
  13.       
  14.     <meta http-equiv="pragma" content="no-cache">  
  15.     <meta http-equiv="cache-control" content="no-cache">  
  16.     <meta http-equiv="expires" content="0">      
  17.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  18.     <meta http-equiv="description" content="This is my page">  
  19.     <!-- 
  20.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  21.     -->  
  22.   
  23.   </head>  
  24.     
  25.   <body>  
  26.       
  27.     用戶名:${requestScope.usename } <br/>  
  28.     文件:${requestScope.file1 }<br/>  
  29.     ${requestScope.file2 }<br/>  
  30.     <!-- 把上傳的圖片顯示出來 -->  
  31.     <img alt="go" src="upload/<%=(String)request.getAttribute("file1")%> " />  
  32.       
  33.       
  34.       
  35.   </body>  
  36. </html>  


4結果頁面:

 

相關文章
相關標籤/搜索