1. 程式人生 > >Servlet實現檔案上傳,可多檔案上傳

Servlet實現檔案上傳,可多檔案上傳

一、Servlet實現檔案上傳,需要新增第三方提供的jar包

下載地址:

接著把這兩個jar包放到 lib資料夾下

二:

檔案上傳的表單提交方式必須是POST方式,

編碼型別:enctype="multipart/form-data",預設是 application/x-www-form-urlencoded

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

三、舉例

1.fileupload.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'fileupload.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
     <!-- enctype 預設是 application/x-www-form-urlencoded -->
     <form action="FileUpLoad" enctype="multipart/form-data" method="post" >
        
               使用者名稱:<input type="text" name="usename"> <br/>
               上傳檔案:<input type="file" name="file1"><br/>
              上傳檔案: <input type="file" name="file2"><br/>
              <input type="submit" value="提交"/>
     
     </form>
     
     
     
  </body>
</html>

2.實際處理檔案上傳的 FileUpLoad.java
package com.servlet.fileupload;

import java.io.File;
import java.io.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * 
 * @author Administrator
 * 檔案上傳
 * 具體步驟:
 * 1)獲得磁碟檔案條目工廠 DiskFileItemFactory 要導包
 * 2) 利用 request 獲取 真實路徑 ,供臨時檔案儲存,和 最終檔案儲存 ,這兩個儲存位置可不同,也可相同
 * 3)對 DiskFileItemFactory 物件設定一些 屬性
 * 4)高水平的API檔案上傳處理  ServletFileUpload upload = new ServletFileUpload(factory);
 * 目的是呼叫 parseRequest(request)方法  獲得 FileItem 集合list ,
 *     
 * 5)在 FileItem 物件中 獲取資訊,   遍歷, 判斷 表單提交過來的資訊 是否是 普通文字資訊  另做處理
 * 6)
 *    第一種. 用第三方 提供的  item.write( new File(path,filename) );  直接寫到磁碟上
 *    第二種. 手動處理  
 *
 */
public class FileUpLoad extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		request.setCharacterEncoding("utf-8");	//設定編碼
		
		//獲得磁碟檔案條目工廠
		DiskFileItemFactory factory = new DiskFileItemFactory();
		//獲取檔案需要上傳到的路徑
		String path = request.getRealPath("/upload");
		
		//如果沒以下兩行設定的話,上傳大的 檔案 會佔用 很多記憶體,
		//設定暫時存放的 儲存室 , 這個儲存室,可以和 最終儲存檔案 的目錄不同
		/**
		 * 原理 它是先存到 暫時儲存室,然後在真正寫到 對應目錄的硬碟上, 
		 * 按理來說 當上傳一個檔案時,其實是上傳了兩份,第一個是以 .tem 格式的 
		 * 然後再將其真正寫到 對應目錄的硬碟上
		 */
		factory.setRepository(new File(path));
		//設定 快取的大小,當上傳檔案的容量超過該快取時,直接放到 暫時儲存室
		factory.setSizeThreshold(1024*1024) ;
		
		//高水平的API檔案上傳處理
		ServletFileUpload upload = new ServletFileUpload(factory);
		
		
		try {
			//可以上傳多個檔案
			List<FileItem> list = (List<FileItem>)upload.parseRequest(request);
			
			for(FileItem item : list)
			{
				//獲取表單的屬性名字
				String name = item.getFieldName();
				
				//如果獲取的 表單資訊是普通的 文字 資訊
				if(item.isFormField())
				{					
					//獲取使用者具體輸入的字串 ,名字起得挺好,因為表單提交過來的是 字串型別的
					String value = item.getString() ;
					
					request.setAttribute(name, value);
				}
				//對傳入的非 簡單的字串進行處理 ,比如說二進位制的 圖片,電影這些
				else
				{
					/**
					 * 以下三步,主要獲取 上傳檔案的名字
					 */
					//獲取路徑名
					String value = item.getName() ;
					//索引到最後一個反斜槓
					int start = value.lastIndexOf("\\");
					//擷取 上傳檔案的 字串名字,加1是 去掉反斜槓,
					String filename = value.substring(start+1);
					
					request.setAttribute(name, filename);
					
					//真正寫到磁碟上
					//它丟擲的異常 用exception 捕捉
					
					//item.write( new File(path,filename) );//第三方提供的
					
					//手動寫的
					OutputStream out = new FileOutputStream(new File(path,filename));
					
					InputStream in = item.getInputStream() ;
					
					int length = 0 ;
					byte [] buf = new byte[1024] ;
					
					System.out.println("獲取上傳檔案的總共的容量:"+item.getSize());

					// in.read(buf) 每次讀到的資料存放在   buf 陣列中
					while( (length = in.read(buf) ) != -1)
					{
						//在   buf 陣列中 取出資料 寫到 (輸出流)磁碟上
						out.write(buf, 0, length);
					    
					}
					
					in.close();
					out.close();
				}
			}
			
			
			
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (Exception e) {
			// TODO Auto-generated catch block
			
			//e.printStackTrace();
		}
		
		
		request.getRequestDispatcher("filedemo.jsp").forward(request, response);
		

	}

}

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

3.filedemo.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'filedemo.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    
    使用者名稱:${requestScope.usename } <br/>
    檔案:${requestScope.file1 }<br/>
    ${requestScope.file2 }<br/>
    <!-- 把上傳的圖片顯示出來 -->
    <img alt="go" src="upload/<%=(String)request.getAttribute("file1")%> " />
    
    
    
  </body>
</html>

4結果頁面


下載連結:

1)Servlet 檔案上傳 ———— 點選開啟連結

2)Struts2之下載  點選開啟連結

3)Struts2之上傳  點選開啟連結