Tuesday, March 16, 2010

Upload Files with JSF, JAVA & Seam

About 4-5 years ago, I learned in Java about how to make a File dialog box appears. I haven't used it about file dialog boxes in my projects. So, I was excited when I had the idea to allow users to upload simple PDFs file without them having to ask me to do it. I know it is going to be a bit extensive work for me on top of what I have to accomplish before the next deployment. But I'm sure that procrastination is the habit of almost all the programmers.

So, I'm going to use Seam's s:fileUpload to allow users to upload a file. s:fileUpload comes with a browse button which allows you to browse through the files in your local disk. The first step for me was to learn how to use that fileUpload tag.

In order to use s:fileUpload, it is mandatory that it's inside either a4j:form or h:form which has enctype="multipart/form-data". In my case, it's like this :

a4j:form id="uploadTA" enctype="multipart/form-data"

Then in the backing bean or POJO, I need to specify either an inputstream or byte array to hold the file's data. The way Seam passes the file information is inside data attribute of s:fileupload. So, it'll be like :

s:fileupload data="#{fileUpload.file}" accept="application/pdf"

fileUpload is my backing POJO and file is a byte[] array. I can't use an injection and outjection attribute for my byte[] array. You will need to use getters and setters otherwise you will get an exception.

If you are up to this part, then all you are left with was how to save the file data on the server hard disk. s:fileUpload only allows you to hold the file's data into a byte array. If you want to have a file, then you need to do a little more work. You will need a button that will call an action method to do the work. So, I have the following on my jsf page :

h:commandbutton action="#{fileUpload.upload()}" value="Upload"

The upload() method looks like this :

public void upload() throws IOException{
if(file.length != 0){
//you can specify the name you want and the path inside File() object's constructor
OutputStream out = new FileOutputStream(new File("file.pdf"));
out.write(file);
out.close();
log.info("Successfully created file");

}else{
log.info("file size is either null or 0");
}
}

No comments:

Post a Comment