Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...