I am looking around a few blogs, to try to find how to upload files using JSF 2.0 But all the solutions kind of confuse me. I would like to know what do I exactly need to be able to successfully upload a file(MP3, PDF, video... what ever type) and store it in a database as a @Lob. This is what I have done so far:
I created an entity that has an attribute of type byte[] and it is also annotated with a @Lob annotation.
I created an EJB that will introduce the entity with with a method that has a byte[] as a parameter and inserts it into the database using the EntityManager class( persist method).
I created a JSF page with an input tag of type "file" and a submit button
I prepared a managed bean to interchange information about the file with the JSF page.
Now I am stuck, and I have lots of doubts:
What should I do to pass the file from the JSF to the managed bean and then transform it to a byte[](To be able to handle it over to the EJB)?
How can a servlet help me?
Do I need a servlet to do this?
Also I found that in some blog it mentions something about servlets 3.0, but I don't know if my working environment is using it, how can if I am using servlets 3.0 (I am using JEE6)?
I never did file upload before and also I am not very familiar with servlets. I am confused, someone could give me some starting tips, please?
The easiest way is probably to use the inputFileUpload tag that you can find in MyFaces:
http://myfaces.apache.org/
BalusC's blog post: Uploading files with JSF 2.0 and Servlet 3.0 is what saved me, because I had problems running RichFaces 4 fileUpload tag with Spring WebFlow.
It's worth to modify BalusC's code to use Spring's
MultipartResolver
- you don't need hisMultipartMap
from another blog post.I achieved it by modifying a
decode
method inFileRenderer
like this:A
UploadedFile
is a simple serializable POJO used to return results to backing bean.For completeness, I just want to provide a fully functional self contained example of how this is done with JSF 2.2, either with non-Ajax and Ajax requests. Keep in mind JSF 2.2 uses different namespaces and you need to be working with a Servlet 3.0 container (as Tomcat 7.0.x, JBoss AS 6.x and 7.x and GlassFish 3.x are).
fileUpload.xhtml
UploadBean.java:
See also:
In JSF 2.2 you can easily upload file using tag without using commons-io or filter. This tag support both normal and ajax process.
Normal:
Ajax:
Design your managed bean as follows:
I would recommend using a companent library like Tomahawk's
<t:inputFileUpload>
or PrimeFaces<p:fileUpload>
.BalusC also has a nice blog post about Uploading files with JSF 2.0 and Servlet 3.0.
IceFaces2.0 has one, http://wiki.icefaces.org/display/ICE/FileEntry Haven't tried implementing it yet, but the download has sample apps and it works under Tomcat 6 (servlet 2.5, so not JEE6)