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[]
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With