commons-fileupload-1.0上傳組件使用實例.

commons-fileupload-1.0上傳組件使用實例.

 文件上傳一個WEB開發的基本功能, 以前做項目的時候,自己寫過組件,也用過別人寫的組件,感覺效果都不是很好,最的發現commons-fileupload是一個很不錯的選擇,從功能,文檔,技術背景都相當不錯.

花一天時間. 從API到網上看資料. 終於可以在我的項目中用它了. 在這裏做一個總結, 也希望對想用這個組件的朋友有所幫助.


FileItem類,它包括了單個表單屬性的所有資料,所有表單值都可以通過它來取得.

主要有以下方法.具體用途請參考API.

          void delete()
          getContentType()
          getFieldName()
          getInputStream()
          getName()
          getOutputStream()
          getString()
          getString(java.lang.String encoding)
          isFormField()
          isInMemory()
          setFieldName(java.lang.String name)
          setFormField(boolean state)
          write(java.io.File file)

以下是使用的一個實例. 具體方法都可以從commons-fileupload的API文件中找到,不再多說..


上傳頁面;

up.jsp

<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>

<body>
<form action="up1.jsp" method="post" enctype="multipart/form-data" name="form1">
  <input name="thisfile" type="file" id="thisfile">
  <input name="user" type="text" id="user" size="10">
  <input type="submit" name="Submit" value="Submit">
</form>
</body>
</html>

後端處理頁面

up1.jsp

<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>

<body>
<%
   try{
        String dir=request.getRealPath(".");
        DiskFileUpload fu = new DiskFileUpload();
       
        fu.setSizeMax(4194304);                 //設置文件大小.

        fu.setSizeThreshold(4096);              //設置緩衝大小.

        fu.setRepositoryPath(dir+"/test");      //設置臨時目錄.
  
 List fileItems = fu.parseRequest(request);   //解析請求,返回一個集合.
       
        Iterator i = fileItems.iterator();

        while(i.hasNext())
     {
    
            FileItem fi = (FileItem)i.next();
   
    if(fi.isFormField())                        //這是用來確定是否爲文件屬性,
     {

                        String fieldName = fi.getFieldName();     //這裏取得表單名
   String fieldvalue=fi.getString();         //這裏取得表單值

   out.print("<br>");
   out.print("name:"+fieldName);
                        out.print("value:"+fieldvalue);
                   }
     else                                           //這裏開始外理文件
     {
                       String fileName = fi.getName();            // 返回文件名包括客戶機路徑
                       if(fileName!=null)
      {
        out.print(fileName);
        out.print("<br>"+fi.getFieldName());  // 打印文件表單名
         
                             fi.write(new File(dir+"/test/a.jpg"));     // 寫文件到服務器.
      }
    }
            }
   }
  catch(Exception e)
   {}

 %>

</body>
</html>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章