java基礎篇---文件上傳(commons-FileUpload組件)


上一篇講解了smartupload組件上傳,那么這一篇我們講解commons-FileUpload組件上傳

FileUpload是Apache組織(www.apache.org)提供的免費的上傳組件,可以直接從Apache站點上下載(下載地址:http://commons.apache.org/fileupload/),本文使用的版本是1.2.1,但是FileUpload組件本身還依賴於commons組件,所以從Apache下載此組件的時候還需要連同commons組件的IO包一起下載(下載地址:http://commons.apache.org/io/) 
commons-fileUpload上傳組件對中文進行了良好的處理,對上傳文件不會出現中文亂碼問題,是目前最廣泛的組件,
將commons-fileupload-1.2.1.jar和commons-io-1.4.jar配置到TOMCAT_HOME/lib/目錄中
³FileUpload的具體上傳操作與SmartUpload相比有着很高的復雜度,下面來看一看FileUpload上傳的基本步驟:
  1. 1創建磁盤工廠:DiskFileItemFactory factory = new DiskFileItemFactory();
  2. 創建處理工具:ServletFileUpload upload = new ServletFileUpload(factory);
  3. 設置上傳文件大小:upload.setFileSizeMax(3145728);
  4. 接收全部內容:List<FileItem> items = upload.parseRequest(request);
  上傳原理
使用fileupload組件接收完全部的數據之后,所有的數據都保存在了List集合之中,則就需要使用Iterator輸出每一個,但是由於其中既有普通的文本數據又有上傳的文件,每一個上傳內容都使用一個FileItem類對象表示。
所以當使用Iterator依次取出每一個FileItem對象的時候,就可以使用FileItem類中的isFormField()方法來判斷當前操作的內容是普通的文本還是上傳文件,如果是上傳文件,則將文件的內容依次取出;如果是普通的文本,則直接通過getString()方法取得具體的信息。
 
 
組件上傳代碼實例一
html代碼
<html>
<head><title>commons-FileUpload組件上傳</title></head>
<body>
<form action="fileupload_demo01.jsp" method="post" enctype="multipart/form-data"> 
    姓名:<input type="text" name="uname"><br>
    照片:<input type="file" name="pic"><br>
    <input type="submit" value="上傳">
    <input type="reset" value="重置">
</form>
</body>
</html>

jsp代碼

<%@ page contentType="text/html" pageEncoding="GBK"%>
<%@ page import="java.util.*"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<html>
<head><title>commons-FileUpload組件上傳</title></head>
<body>
<%
    DiskFileItemFactory factory = new DiskFileItemFactory() ;
    ServletFileUpload upload= new ServletFileUpload(factory) ;
    upload.setFileSizeMax(3 * 1024 * 1024) ;    // 只能上傳3M
    List<FileItem> items = upload.parseRequest(request) ; // 接收全部內容
    Iterator<FileItem> iter = items.iterator() ;
    while(iter.hasNext()){
        FileItem item = iter.next() ;
        String fieldName = item.getFieldName() ;    // 取得表單控件的名稱
%>
        <ul><h4><%=fieldName%> --> <%=item.isFormField()%></h4>
<%
        if(!item.isFormField()){        // 不是普通文本
            String fileName = item.getName() ;    // 取得文件的名稱
            String contentType = item.getContentType() ;    // 文件類型
            long sizeInBytes = item.getSize() ;
%>
            <li>上傳文件名稱:<%=fileName%>
            <li>上傳文件類型:<%=contentType%>
            <li>上傳文件大小:<%=sizeInBytes%>
<%
        } else {
            String value = item.getString() ;
%>
            <li>普通參數:<%=value%>
<%
        }
%>        </ul>
<%
    }
%>
</body>
</html>

組件上傳代碼實例二

<html>
<head><title>commons-FileUpload組件上傳</title></head>
<body>
<form action="fileupload_demo02.jsp" method="post" enctype="multipart/form-data"> 
    姓名:<input type="text" name="uname"><br>
    照片:<input type="file" name="pic1"><br>
    照片:<input type="file" name="pic2"><br>
    照片:<input type="file" name="pic3"><br>
    <input type="submit" value="上傳">
    <input type="reset" value="重置">
</form>
</body>
</html>

JSP代碼

<%@ page contentType="text/html" pageEncoding="GBK"%>
<%@ page import="java.util.*,java.io.*"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="cn.mldn.lxh.util.*"%>
<html>
<head><title>commons-fileUpload組件上傳實例二</title></head>
<body>
<%
    DiskFileItemFactory factory = new DiskFileItemFactory() ;
    factory.setRepository(new File(this.getServletContext().getRealPath("/") + "uploadtemp")) ;        // 更准確的說是一個臨時文件
    ServletFileUpload upload = new ServletFileUpload(factory) ;
    upload.setFileSizeMax(3 * 1024 * 1024) ;    // 只能上傳3M
    List<FileItem> items = upload.parseRequest(request) ; // 接收全部內容
    Iterator<FileItem> iter = items.iterator() ;
    IPTimeStamp its = new IPTimeStamp(/* request.getRemoteAddr() */) ;
    while(iter.hasNext()){
        FileItem item = iter.next() ;
        String fieldName = item.getFieldName() ;    // 取得表單控件的名稱
%>
        <ul><h4><%=fieldName%> --> <%=item.isFormField()%></h4>
<%
        if(!item.isFormField()){        // 不是普通文本
            File saveFile = null ;
            InputStream input = null ;
            OutputStream output = null ;
            input = item.getInputStream() ;
             output = new FileOutputStream(new File(this.getServletContext().getRealPath("/")+"upload"+File.separator+its.getIPTimeRand()+"."+item.getName().split("\\.")[1])) ;
             int temp = 0 ;
            byte data[] = new byte[512] ;
            while((temp=input.read(data,0,512))!=-1){
                output.write(data) ;    // 分塊保存
            }
            input.close() ;
            output.close() ;  
        } else {
            String value = item.getString() ;
%>
            <li>普通參數:<%=value%>
<%
        }
%>        </ul>
<%
    }
%>
</body>
</html>

注意:本代碼在建立項目時需要在項目名稱下創建upload文件夾才能正常運行。

FileUpload組件的不便之處:

  1. 無法像使用request.getParameter()方法那樣准確的取得提交的參數;
  2. 無法像使用request.getParameterValues()那樣准確的取得一組提交參數;
  3. 所有的上傳文件都需要進行依次的判斷,才能夠分別保存,不能一次性批量保存。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM