戰地連結︰ Home My Flickr NBA.com About

2008年7月22日星期二

Uploading Multiple Files using Struts FormFile

Overview

It is convenient to group same type of Form Inputs with an ArrayList (or other types of List). For checkbox this is easily done in Struts Framework, but how about "File" or other types of input?

Reference

Uploading Multiple Files using Struts FormFile

Code Snippet

I copy the code from the reference link above and do some change on it in order to get the uploaded files in the order shown in the User's Form.

In JSP File

<form name="fileupload" enctype="multipart/form-data" method="post" action="/photos/fileuploadresult">

    <tr>

        <td>Photo 1</td>

        <td><input type="file" name="uploads[0]" /></td>

    </tr>

    <tr>

        <td>Photo 2</td>

        <td><input type="file" name="uploads[1]" /></td>

    </tr>

    <tr>

        <td><input type='submit' name="submit" value="Submit"></td>

    <tr>

</form>

In struts-config.xml

<action path="/photos/fileuploadresult" type="com.uploads.actions.FileUploadAction" name="PhotoUpload" scope="request" >

    <forward name="success" path="/photos/fileuploadresult.jsp" />

</action>

 

<form-bean name="PhotoUpload" type="com.uploads.forms.FileUploadForm">

</form-bean>

In FileUploadForm.java

  public class FileUploadForm extends ActionForm {

    private List formFiles = new ArrayList();

    public List getUploads() {
      return this.formFiles;
    }

    public void setUploads(int iIndex, FormFile formFile) {
      if ( !formFile.getFileName().equals("") ) {
        if ( this.formFiles.size() <= iIndex ) {
          // Fill the list to the specified size
          for ( int i=this.formFiles.size(); i < iIndex; i++ ){
            this.formFiles.add(null);
          }
          this.formFiles.add(formFile);
        } else {
          this.formFiles.set(iIndex, formFile);
        }
      }
    }

  }

沒有留言: