天天看點

Struts 2檔案上傳

 (1)       基于表單的檔案上傳

在建立表單是,不要忘了使用enctype屬性,并将它的值指定為multipart/form-date。表單enctype屬性的預設值是application/x-www-form-urlencoded,這種編碼方案使用有限的字元集,當使用了非字母和數字的字元時,必須使用“%HH”代替(這裡的H表示的十六進制數字)。

表單的method為post。

(2)       檔案上傳内容分析

對于檔案上傳來說,要讀取檔案的内容,不能使用ServletRequest接口的getParameter()方法,而需要調用ServletRequest接口的geInputSlream()方法來得到輸入流,然後從輸入流中讀取傳送的内容,再根據檔案上傳的格式進行分析,取出上傳檔案的内容和衣單中其他字段的内容。

(3)       Struts 2對檔案上傳的支援

Ⅰ:需要的JAR包:

Ø  commons-fileupload-1.2.1.jar

Ø  commons-io-1.3.2.jar

Ⅱ:Struts 2提供了一個文檔上傳的攔截器:org.apache.struts2.interceptor.FileUploadInterceptor。他負責調用底層的檔案上傳元件解析檔案内容,并為Action準備與上傳檔案相關的屬性值。處理檔案請求的Action必須提供特殊式命名的屬性。例如,若表單中檔案選擇框<input tepy=”file” name=”image”>

UpfileAction.java

import java.io.BufferedInputStream; 

import java.io.BufferedOutputStream; 

import java.io.File; 

import java.io.FileInputStream; 

import java.io.FileOutputStream; 

import java.util.Date; 

import org.apache.struts2.ServletActionContext; 

import com.opensymphony.xwork2.ActionSupport; 

public class UpfileAction extends ActionSupport { 

    private File file; 

    private String fileFileName; 

    private String fileContentType; 

    private String description; 

    //省略getter與setter方法 

    @Override 

    public String execute() throws Exception { 

        String newFileName=null; 

        long time =new Date().getTime();                //時間 

        String path= ServletActionContext.getServletContext().getRealPath("upfile");//儲存上傳檔案的目錄 

        File dir= new File(path);                       //建立目錄 

        if(!dir.exists()){ 

            dir.mkdir(); 

        } 

        int index=fileFileName.lastIndexOf("."); 

        if (index ==-1) { 

            newFileName=fileFileName.substring(0,index)+"-"+ time;  //檔案名 

        } else { 

            newFileName =fileFileName.substring(0,index)+"-"+time+fileFileName.substring(index); 

        BufferedInputStream bin=null; 

        BufferedOutputStream bout=null; 

        try { 

            FileInputStream fin =new FileInputStream(file); 

            bin=new BufferedInputStream(fin); 

            FileOutputStream fout =new FileOutputStream(new File(dir, newFileName)); 

            bout=new BufferedOutputStream(fout); 

            byte[] b=new byte[1024]; 

            int len=0; 

            while ((len=bin.read(b))!=-1) { 

                bout.write(b, 0, len); 

            } 

        } catch (Exception e) { 

            System.out.println("寫出資料失敗!!!!"); 

        }finally{ 

            try { 

                bout.close(); 

                bin.close(); 

            } catch (Exception e2) { 

                System.out.println("關閉資料流失敗!!!!"); 

        return SUCCESS; 

    } 

upfile.jsp:

<body> 

    <s:form action="upfile" method="post" enctype="multipart/form-data"  > 

        <s:file name="file" label="選擇上傳的檔案"></s:file><br> 

        <s:textfield name="description" label="檔案描述"></s:textfield> 

        <s:submit value="上傳"></s:submit> 

    </s:form> 

  </body> 

success.jsp:

    <center> 

        <h1> 

            <font color="red"> 

                檔案名:<s:property value="fileFileName"/><br> 

                檔案類型:<s:property value="fileContentType"/><br> 

                檔案描述:<s:property value="description"/><br> 

            </font> 

        </h1> 

    </center> 

struts.xml:

<!-- 設定上傳檔案的最大長度 --> 

    <constant name="struts.multipart.maxSize" value="102400000"></constant> 

    <package name="upfile" extends="struts-default"> 

        <action name="upfile" class="com.mzsx.upfile.UpfileAction"> 

            <result name="success">/s16/success.jsp</result> 

            <result name="input">/s16/upfile.jsp</result> 

        </action> 

    </package> 

UpfileListAction.java

import java.util.List; 

public class UpfileListAction extends ActionSupport { 

    private List<File> file; 

    private List<String> fileFileName; 

    private List<String> fileContentType; 

    private List<String> description; 

        for (int i=0;i<file.size();i++) { 

            int index=fileFileName.get(i).lastIndexOf("."); 

            if (index ==-1) { 

                newFileName=fileFileName.get(i).substring(0,index)+"-"+ time;   //檔案名 

            } else { 

                newFileName =fileFileName.get(i).substring(0,index)+"-"+time+fileFileName.get(i).substring(index); 

            BufferedInputStream bin=null; 

            BufferedOutputStream bout=null; 

                FileInputStream fin =new FileInputStream(file.get(i)); 

                bin=new BufferedInputStream(fin); 

                FileOutputStream fout =new FileOutputStream(new File(dir, newFileName)); 

                bout=new BufferedOutputStream(fout); 

                byte[] b=new byte[1024]; 

                int len=-1; 

                while ((len=bin.read(b))!=-1) { 

                    bout.write(b, 0, len); 

                } 

            } catch (Exception e) { 

                System.out.println("寫出資料失敗!!!!"); 

            }finally{ 

                try { 

                    bout.close(); 

                    bin.close(); 

                } catch (Exception e2) { 

                    System.out.println("關閉資料流失敗!!!!"); 

    <s:form action="upfilelist" method="post" enctype="multipart/form-data"  > 

注意:所有file同名。 

struts.xml

    <package name="upfilelist" extends="struts-default"> 

        <action name="upfilelist" class="com.mzsx.upfile.UpfileListAction"> 

            <result name="success">/s16/successList.jsp</result> 

            <result name="input">/s16/upfileList.jsp</result> 

本文轉自 夢朝思夕 51CTO部落格,原文連結:http://blog.51cto.com/qiangmzsx/1143464