JSF portlet file upload

File upload functionality is very common to most of the portlet/web applications.
In portlet, file upload is treated a bit different than usual web application file uploads.
If it is a non-jsf portlet, you might need to use any third party file upload component like Apache commons file upload portlet.

Here I am writing steps to implement file upload functionality in JSR JSF portlet.

1) JSP code
  1.1) Declaring enctype attribute of form
        Form enctype attribute value should be set to multipart/form-data
      
 <h:form styleClass="create-listing-form" enctype="multipart/form-data">


   1.2) Component to browse file from file system
 
            <hx:fileupload id="logoUpload"
            tabindex="26">
                <hx:fileProp name="fileName" />
                <hx:fileProp name="contentType" />                              
            </hx:fileupload>  

2) JSF managed bean code
   
protected HtmlFileupload logoUpload;  // declare this as instance variable
  
    2.1) Method to get HtmlFileUpload object for the uploaded file
  
        protected HtmlFileupload getLogoUpload() {
              
            if (logoUpload != null) {
               logoUpload = (HtmlFileupload) findComponentInRoot("logoUpload");
             }
                return logoUpload;  
        }
  
 2.2) UploadFile method to get file bytestream and process it further to store in DB or onto file system as per the requirement.
  
         public void uploadFile(){
      
       ContentElement content = (ContentElement) getLogoUpload().getValue();
               

         if(content!=null){
               

// further validation can be applied with the help of ContentElement object to check type of file(image,text,doc) or maximum upload size to be allowed
                  
              ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(content.getContentValue());
                   

// convert to inputStream to set as BinaryStream to CallableStatement object


                    InputStream inputStream = byteArrayInputStream;
              
                    // writing to another file on the file system
                  
                    File outputFilename = new File(<FilePath>);
    
                    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(<OutputFilename>));
                    int data;
                    while((data=byteArrayInputStream.read())!=-1) {
                        char ch = (char)data;
                        bufferedOutputStream.write(ch);
                    }
          
                    bufferedOutputStream.flush();
                    bufferedOutputStream.close();
                    byteArrayInputStream.close();
                    inputStream.close();
              
                }
      
         }

No comments: