5
votes

How to insert uploaded image from p:fileUpload as BLOB in MySQL?

@Lob
@Column(name = "photo")
private byte[] photo;

And in XHTML page, I write this:

<p:inputText value="#{condidat.condidat.photo}" >
<p:fileUpload fileUploadListener="#{fileUploadController.handleFileUpload}"   
    allowTypes="*.jpg;*.png;*.gif;" description="Images"/>                       
</p:inputText>

How can I retreive the value of uploaded file as byte[]?

2
An Error Occurred: javax.validation.ConstraintViolationException: Bean Validation constraint(s) violated while executing Automatic Bean Validation on callback event:'prePersist'. Please refer to embedded ConstraintViolations for details.Abdennour TOUMI
You have to play with the StreamedContent received from the fileUpload component. You have an example in the showcase. What version of PF do you use? Once you have the streamedContent, you can insert it in DB.spauny

2 Answers

8
votes

You can get the uploaded file content via FileUploadEvent. In PrimeFaces 4.x with Apache Commons FileUpload, or in PrimeFaces 5.x with context param primefaces.UPLOADER set to commons, you can use UploadedFile#getContents() to obtain the uploaded file as byte[].

public void handleFileUpload(FileUploadEvent event) {
    byte[] content = event.getFile().getContents();
    // ...
}

In PrimeFaces 5.x with context param primefaces.UPLOADER absent or set to auto or native while using JSF 2.2, then getContents() will return null as that's not implemented in NativeUploadedFile implementation. Use UploadedFile#getInputStream() instead and then read bytes from it, e.g. with help of commons IO.

public void handleFileUpload(FileUploadEvent event) {
    byte[] content = IOUtils.toByteArray(event.getFile().getInputstream());
    // ...
}

Finally, just set this byte[] in your entity and persist/merge it.

Make sure that you have set the form encoding type to multipart/form-data and, when using the Apache Commons FileUpload, that you have configured the file upload filter in web.xml as per PrimeFaces user guide.

0
votes

It might be helpful to mention that, I had to use:

public void handleUpload(FileUploadEvent e) throws Exception {
    byte[] contents = IOUtils.toByteArray(e.getFile().getInputstream());
    //....
}

As it seems that in PrimeFaces 5.x, the getContents() always returns null !