如何在 MySQL 中插入从 p:fileUpload 上传的图像作为 BLOB? [英] How to insert uploaded image from p:fileUpload as BLOB in MySQL?
问题描述
如何在 MySQL 中插入从 p:fileUpload 上传的图片作为 BLOB?
How to insert uploaded image from p:fileUpload as BLOB in MySQL?
@Lob
@Column(name = "photo")
private byte[] photo;
在 XHTML 页面中,我写了这个:
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>
如何将上传文件的值检索为byte[]
?
How can I retreive the value of uploaded file as byte[]
?
推荐答案
您可以通过FileUploadEvent
获取上传的文件内容.在带有 Apache Commons FileUpload 的 PrimeFaces 4.x 中,或在上下文参数 primefaces.UPLOADER
设置为 commons
的 PrimeFaces 5.x 中,您可以使用 UploadedFile#getContents()
获取上传的文件为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();
// ...
}
在 PrimeFaces 5.x 中,上下文参数 primefaces.UPLOADER
不存在或设置为 auto
或 native
,同时使用 JSF 2.2,然后 getContents()
将返回 null
因为那是 未在 NativeUploadedFile
实现 中实现.使用 UploadedFile#getInputStream()
代替,然后 读取字节从它,例如在公共 IO 的帮助下.
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());
// ...
}
最后,只需在您的实体中设置此 byte[]
并保留/合并它.
Finally, just set this byte[]
in your entity and persist/merge it.
确保您已将表单编码类型设置为 multipart/form-data
,并且在使用 Apache Commons FileUpload 时,您已配置 web.xml
中的文件上传过滤器根据 PrimeFaces 用户指南.
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.
这篇关于如何在 MySQL 中插入从 p:fileUpload 上传的图像作为 BLOB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!