I am trying to get the uploaded image of <p:fileUpload>
as byte[]
and persist it in DB by JPA. But I'm facing a problem and I'm not even sure if I'm coding it the right way.
This is the entity:
@Entity
class Object {
@Lob
@Column(name = "image")
private byte[] image;
//...
}
Managed bean:
@ManagedBean
class MyBean {
private Object ob = new Object();
@EJB
private ObjectFacadeLocal of;
public void handleFileUpload(FileUploadEvent event) {
byte[] content = event.getFile().getContents();
ob.setImage(content);
}
public String submit() {
//...
of.create(ob);
return "anotherpage"
}
The ObjectFacade
persists Object
in database.
This is the JSF page called form.xhtml
:
<h:form id = "upi" enctype = "multipart/form-data">
<p:fileUpload fileUploadListener="#{MyBean.handleFileUpload}"
allowTypes="*.jpg;*.png;*.gif;" description="Images"/>
<h:commandButton value = "Submit" action = "#{MyBean.create()}">
</h:commandButton>
</h:form>
First of all, I'm getting a warning in form.xhtml
that it cannot find the handleFileUpload
method, but I can still run it. When I press the submit button, then nothing happens, the page just refreshes. If I remove the enctype
attribute then the object gets persisted, but not with the image.
Any ideas?
Update:
This is my web.xml
file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee /web-app_3_0.xsd">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/blog.xhtml</welcome-file>
</welcome-file-list>
<filter>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
</web-app>