Big File Upload Tutorial Using Seam



Most of the available examples for file upload in Seam suits only upload of small files as the target is a byte array. We may end up facing  out of memory exception when we upload large files using JBoss Seam. Hence to avoid this, we have to declare the target variable as InputStream instead of byte[].

@Name("studentAction")
@Scope(ScopeType.PAGE)
public class StudentAction implements Serializable {

    @In(create = true)
    private Student student;
    @In(create = true)
    private EntityManager em;
    @In
    private FacesMessages facesMessages;
    private InputStream uploadedFile; //along with getter and setter for uploadedFile
    private String pictureName; //along with getter and setter for pictureName

This will be set in the UI as below.

<s:fileUpload data="#{studentAction.uploadedFile}" fileName="#{studentAction.pictureName}"/>

In the usual way we store this into a File on the server [For convenience I have provided the not so refined code snippet below].

//saveToDisk is a method in StudentAction

  public void saveToDisk(String location){

        FileOutputStream fos = null;
       
           try {
            File file = new File(location+fileName);
            fos = new FileOutputStream(file);
            byte[] b=new byte[102400];
            int readCnt=0;
            while((readCnt=uploadedFile.read(b))!= -1){
                fos.write(b, 0, readCnt);
                fos.flush();
            }

            } catch (Exception ex) {
            java.util.logging.Logger.getLogger(UploadFile.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fos.close();
            } catch (IOException ex) {
                java.util.logging.Logger.getLogger(UploadFile.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

The other settings required for enabling file upload in Seam are

In components.xml

 <web:multipart-filter create-temp-files="true" max-request-size="100000000" url-pattern="*.seam"/>

In the UI the form should have enctype as multipart/form-data

 <h:form id="addstudent" enctype="multipart/form-data">

In web.xml

  <filter>
        <filter-name>Seam Multipart Filter</filter-name>
        <filter-class>org.jboss.seam.web.MultipartFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>Seam Multipart Filter</filter-name>
        <url-pattern>*.seam</url-pattern>
    </filter-mapping>


 
 
 
 
Comments:

Post a Comment:
  • HTML Syntax: Allowed
 

« January 2009
SunMonTueWedThuFriSat
    
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
       
Today

Valid XHTML or CSS?

[This is a Roller site]
 
© Karthik