Servlet實現文件上傳

一.組件準備css

         Servlet實現文件上傳,須要添加第三方提供的jar包
         commons-fileupload-1.2.2-bin.zip 
         commons-io-2.3-bin.zip    
        在
http://commons.apache.org/downloads/index.html找,而後放在以下目錄下html

         image

        文件上傳的表單提交方式必須是POST方式,
         編碼類型:enctype="multipart/form-data",默認是 application/x-www-form-urlencoded
java

文件上傳
  具體步驟:
* 1)得到磁盤文件條目工廠 DiskFileItemFactory 要導包
* 2) 利用 request 獲取 真實路徑 ,供臨時文件存儲,和 最終文件存儲 ,這兩個存儲位置可不一樣,也可相同
* 3)對 DiskFileItemFactory 對象設置一些 屬性
* 4)高水平的API文件上傳處理  ServletFileUpload upload = new ServletFileUpload(factory); 目的是調用 parseRequest(request)方法  得到 FileItem 集合list (一次上傳多個文件,意思是多個input file)
* 5)在 FileItem 對象中 獲取信息,   遍歷, 判斷 表單提交過來的信息 是不是 普通文本信息  另作處理
* 6)
*    第一種. 用第三方 提供的  item.write( new File(path,filename) );  直接寫到磁盤上
*    第二種. 手動處理  
apache

二.理論準備數組

          base標籤只能放置在head標籤內,只有href和target,全部瀏覽器都支持head標籤,裏面的title是惟一必須的。<base> 標籤爲頁面上的全部連接規定默認地址或默認目標。一般狀況下,瀏覽器會從當前文檔的 URL 中提取相應的元素來填寫相對 URL 中的空白。使用 <base> 標籤能夠改變這一點。瀏覽器隨後將再也不使用當前文檔的 URL,而使用指定的基本 URL 來解析全部的相對 URL。這其中包括 <a>、<img>、<link>、<form> 標籤中的 URL。瀏覽器

<html>
<head>
<base href="http://www.w3school.com.cn/i/" />
<base target="_blank" />
</head>
<body>
<img src="eg_smile.gif" /><br />
<p>請注意,咱們已經爲圖像規定了一個相對地址。因爲咱們已經在 head 部分規定了一個基準 URL,瀏覽器將在以下地址尋找圖片:</p>
<p>"http://www.w3school.com.cn/i/eg_smile.gif"</p>
<br /><br />
<p><a href="http://www.w3school.com.cn">W3School</a></p>
<p>請注意,連接會在新窗口中打開,即便連接中沒有 target="_blank" 屬性。這是由於 base 元素的 target 屬性已經被設置爲 "_blank" 了。</p>
</body>
</html>

三.代碼實現緩存

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%  
	//獲得項目的名字,若是項目爲根目錄,則獲得一個"",即空的字條串
	String path = request.getContextPath();  
	//scheme:http
	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<!--  
全部瀏覽器都支持head標籤,裏面的title是惟一必須的。
 <base> 標籤爲頁面上的全部連接規定默認地址或默認目標。
一般狀況下,瀏覽器會從當前文檔的 URL 中提取相應的元素來填寫相對 URL 中的空白。
使用 <base> 標籤能夠改變這一點。瀏覽器隨後將再也不使用當前文檔的 URL,而使用指定的基本 URL 來解析全部的相對 URL。
這其中包括 <a>、<img>、<link>、<form> 標籤中的 URL。
 -->
	<base href="<%=basePath%>">
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>文件上傳</title>
</head>
<body>
	<form action="2.jsp" method="post" enctype="multipart/form-data">
		<label>文件:<input type="file" name="myFile">
		</label><br /> <label>其餘信息:<input type="text" name="info" /></label><br /> <input
			type="submit" value="提交" />
	</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="org.apache.commons.fileupload.servlet.*" %>
<%@page import="org.apache.commons.fileupload.*" %>
<%@page import="org.apache.commons.fileupload.disk.*" %>
<%@page import="java.util.List" %>
<%@page import="java.util.Iterator" %>
<%@page import="java.io.*" %>
<%
	//Check that we have a file upload request
	//監測request中是否包含文件
	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
	if(isMultipart){
		out.print("包含文件");
	}else{
		out.print("不包含文件");
	}
	out.print("<br/>");
	
	// Create a factory for disk-based file items
	FileItemFactory factory = new DiskFileItemFactory();
	//獲取文件須要上傳到的路徑  
   // String path = request.getRealPath("/upload");  
    String path = session.getServletContext().getRealPath("upload");
	 //若是沒如下兩行設置的話,上傳大的 文件 會佔用 不少內存,  
    //設置暫時存放的 存儲室 , 這個存儲室,能夠和 最終存儲文件 的目錄不一樣  
    /** 
     * 原理 它是先存到 暫時存儲室,而後在真正寫到 對應目錄的硬盤上,  
     * 按理來講 當上傳一個文件時,實際上是上傳了兩份,第一個是以 .tem 格式的  
     * 而後再將其真正寫到 對應目錄的硬盤上 
     */  
   // factory.setRepository(new File(path));
    //設置 緩存的大小,當上傳文件的容量超過該緩存時,直接放到 暫時存儲室  
   // factory.setSizeThreshold(1024*1024) ;  
	// Create a new file upload handler
	ServletFileUpload upload = new ServletFileUpload(factory);
	// Parse the request
	List  items = upload.parseRequest(request);
	
	// Process the uploaded items
	Iterator iter = items.iterator();
	while (iter.hasNext()) {
	    FileItem item = (FileItem) iter.next();
	    if (item.isFormField()) {//若是是普通表單控件
	    	////獲取表單的屬性名字  
	    	String name = item.getFieldName();
	    	//獲取用戶具體輸入的字符串 ,名字起得挺好,由於表單提交過來的是 字符串類型的  
	        String value = item.getString();
	    	
	    	request.setAttribute(name,value);
	    	
			out.print("name:"+name +"<br/>");
			out.print("value:"+value +"<br/>");
			
	    } else {//若是是文件
	    	
	    	//也叫name是爲了和上面保持一致,方便顯示頁面
	    	String name = item.getFieldName();
	        String fileName = item.getName();
	        String contentType = item.getContentType();
	        boolean isInMemory = item.isInMemory();
	        long sizeInBytes = item.getSize();
	        
	        out.print("表單文件控件名:"+name +"<br/>");
	        //絕對路徑的
	        out.print("上傳文件名:"+fileName +"<br/>");
	        out.print("文件類型:"+contentType +"<br/>");
	        out.print("是否保存在內存中:"+isInMemory +"<br/>");
	        out.print("大小:"+sizeInBytes +"字節<br/>");
	        
	        //上傳文件
	        //獲取文件名
	        String f_name = fileName.substring(fileName.lastIndexOf("\\")+1,fileName.length());
	        
	        request.setAttribute(name,f_name);
	     	// 進行文件上傳   
            File uploadedFile = new File(path ,f_name);
            item.write(uploadedFile);
            /* 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();  
             */
	    }
	}
	request.getRequestDispatcher("showFile.jsp").forward(request, response);  
%>
<%@ 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>文件展現</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.myfile }<br/>
    <!-- 把上傳的圖片顯示出來 -->
    <img alt="go" src="upload/<%=(String)request.getAttribute("myfile")%> " />
    
  </body>
</html>
          若是有不足或者錯誤的地方,還請指出,不勝感激,願你我共同進步。。。。
相關文章
相關標籤/搜索