Saturday, May 3, 2014

JSF 2.2 FileUpload and a way to get it back

So my Web app needed to be able to upload images for users, "connect" the user and the image and to be able to actually show the image.


Upload:

So JSF 2.2 has a really simple way of doing this. You just put <h:inputFile /> and connect this to a Bean. The type should be "Part" (javax.servlet.http.Part). But to remember is that the <h:form> needs too add enctype="multipart/form-data" as an attribute, <h:form enctype="multipart/form-data">.

Connect:

So now we have a Part in the Bean, but how to save it and where?
Some may want to save the image in the database, this can be done with the BLOB-type. you then have to get the input stream and read it as bytes.

Pros:
All in one place, handled by the DBMS.

Cons:
Database takes much more space
Harder to export all the data for backup-solutions

So what do we do then?
We can save it on the hard drive as regular files. A risk is if the file contains a virus.
How we actually save this is rather easy. The Part-class has a "write"-method which you either can give a relative path or a absolute path. The relative path may put it in the web-applications tmp-folder, it's really the server who controls where its put.

The absolute path makes it easy to do backup scripts to make backups. The big problem is how to reach the files from the web app.

Path:

How to reach files from "above" the web-apps folder is different for the servers. Glassfish has Virtual host/server. Some has context-properties.

The one I have focused on is Wildfly (JBoss Application Server 8).
It was a bit tricky to find the right answer.

But in the config file for your server (domain.conf or one of the standalone confs) there is a subsystem for undertow. Undertow is the new servlet container for JBoss.

In that subsystem there is two parts that's interesting for us right now: Host and Handlers.


In the Handlers part we add
<file name="images-handler" path="your/path/to/save"/>

you can use your servers path-variables

and in the Host part
<location name="/images" handler="images-handler"/>

The handler takes care of where the folder will be retrieved from (read from) and the Host will controll how the web-app will reference it.
In this case you reach it by http://serveradress:port/images

Display:

Now comes the last tricky part. The images-folder is reachable now BUT is reachable by the server-adress WITHOUT the web-apps adress on top of it. You can probably map it to be reachable.

So <graphicImage> gets problems due to it being relative to the web-app.
A simple <img> works great thou.


So either find a way to map it better or use a regular <img>


So that's it for the simple fileUpload of images, especially with Wildfly.

Code ahoy!

No comments:

Post a Comment