Reputation: 181
I have problem regarding displaying image in datagrid column. When Datagrid loads it shows the image correctly but whenever I click on second page or refresh the first page, images are gone. I noticed in the console, clicking on second page or refresh the page made the param value null. That's why Image are not showing. I am using sessionscoped. Below is my code:
public StreamedContent getStreamedImageById() {
FacesContext context = FacesContext.getCurrentInstance();
if (context.getRenderResponse()) {
// So, we're rendering the view. Return a stub StreamedContent so that it will generate right URL.
System.out.println("check");
return new DefaultStreamedContent();
}
else {
// So, browser is requesting the image. Get ID value from actual request param.
String firstName = context.getExternalContext().getRequestParameterMap().get("firstName");
System.out.println("Name:"+firstName);
System.out.println("Image::"+images.get(firstName));
return images.get(firstName);
}
In search method I just take all the images in a hash map.
while(itr.hasNext()){
com.sysvana.request.UserBean us=itr.next();
images.put(us.getFirstName(), stringToStreamedContent(us.getJpegPhoto()));
}
Here is my xhtml::
<p:graphicImage value="#{userManagementActionBean.streamedImageById}" height="40" width="50" style="align:center" >
<f:param id="firstName" name="firstName" value="#{user.firstName}" />
</p:graphicImage>
Upvotes: 0
Views: 1368
Reputation: 1108732
This,
return images.get(firstName);
is not right. You should create the streamed content right there and not return one which is already created before in a previous HTTP request. The whole point is that you should not create it in a previous HTTP request, but directly in the very same HTTP request as the getStreamedImageById()
method is invoked.
Fix it like follows (assuming that userBean.getJpegPhoto()
returns byte[]
)
UserBean userBean = userService.findByFirstName(firstName);
return new DefaultStreamedContent(new ByteArrayInputStream(userBean.getJpegPhoto()));
Unrelated to the concrete problem, the method name stringToStreamedContent()
suggests a major problem. An image is absolutely not to be represented as a String
, but as byte[]
. When treating an image as a String
, you would likely end up in corrupt images due to the information being lost by character encoding issues. You should obtain the image from the DB as byte[]
or InputStream
.
Upvotes: 1