Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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[]?

like image 540
Abdennour TOUMI Avatar asked Nov 29 '11 03:11

Abdennour TOUMI


1 Answers

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.

like image 117
BalusC Avatar answered Nov 15 '22 05:11

BalusC