如何插入上传的图像从p:fileUpload作为BLOB在MySQL中? [英] How to insert uploaded image from p:fileUpload as BLOB in MySQL?

查看:177
本文介绍了如何插入上传的图像从p:fileUpload作为BLOB在MySQL中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从p:fileUpload插入上传的图像作为BLOB在MySQL?

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

在XHTML页面中,我写了这个

 < ; p:inputText value =#{condidat.condidat.photo}> 
< p:fileUpload fileUploadListener =#{fileUploadController.handleFileUpload}
allowTypes =*。jpg; *。png; *。gif;描述= 影像/>
< / p:inputText>

如何将上传的文件的值作为 byte [] <您可以通过 FileUploadEvent 获取上传的文件内容。 $ C>。在使用Apache Commons FileUpload的PrimeFaces 4.x中,或在PrimeFaces 5.x中使用上下文参数 primefaces.UPLOADER 设置为 commons ,您可以使用 UploadedFile#getContents()来获取上传的文件为 byte []


$ b $

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

在带上下文的PrimeFaces 5.x param primefaces.UPLOADER 不存在或设置为 auto native 当使用JSF 2.2时,那么 getContents()将返回 null ,因为它是未在中实现NativeUploadedFile 执行。使用 UploadedFile#getInputStream()代替,然后从它读取字节,例如在公共IO的帮助下
$ b

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

最后,设置

请确保已经将表单编码类型设置为 multipart / form-data ,并且在使用Apache Commons FileUpload时,已经配置了 web.xml 中的文件上传过滤器用户指南。


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.

这篇关于如何插入上传的图像从p:fileUpload作为BLOB在MySQL中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆