File upload using RichFaces

Filip Ekberg picture Filip Ekberg · Oct 22, 2009 · Viewed 16.8k times · Source

I am currently looking in to some file uploading using Java Server Faces. I've found this great introduction to it using RichFaces. However, I have some troubles understanding the process here.

First the user selects a file and if the immediate upload is set to true the file is processed using ajax, so far so good. When it comes to the next step however, the listener on the Bean-side the following confuses me:

public void listener(UploadEvent event) throws Exception{
    UploadItem item = event.getUploadItem();

    File f = item.getFile();

    System.out.println(f.getAbsolutePath());
}

The Absolute path is to a temp directory on my computer, sure I understand that, but how would you make the file available to the webbapplication? My application is deployed as a WAR-file. Is it possible to Upload it to the WAR? Might sound stupid or so, but it might actually be handy.

I am fully aware that I can rename the file to copy it to a new location, but is that the way to go?

Answer

McDowell picture McDowell · Oct 22, 2009

Writing things to your WAR directory (assuming the WAR is even exploded as a directory) is, in generally, a bad idea (for the same reasons that storing your data in your application directory is usually a bad idea).

You'd probably want it to end up in a persistence store, usually a database. Exactly how you manage that is up to you - whether you use the file system and store a reference in the database or store a BLOB in the database directly and whether you use JDBC or JPA or Hibernate, etc.

The list of uploaded files could then be read from the database by refreshing the panel that contained them using something like <a4j:support event="onuploadcomplete" reRender="info" />.

A file download servlet (if RichFaces doesn't have one) is fairly easy to write.