Retrieving blob from database using hibernate and displaying on web page using jsp

Viewed 428

Answer mentioned here This is not working for me I have sent bytes array to the database which is stored as a blob in the database

File file = new File(filePath);
byte[] imageData = new byte[(int) file.length()];

When I try to retrieve the blob object from the database in this byte array

I get a value like this "[B@526d24d9". I send this value to the jsp page.(I am sending a list of blobs to the jsp page i.e a list of bytes array) Now I am trying to render this image on a web page using jsp. But I am not able to figure out the most efficient approach one approach is to retrieve the list of blob ,process it and store it in a file and then retrieve from that filepath in the jsp page using the tag But I am looking for a more efficient approach. I am trying to something like this

jsp code

<c:forEach items="${list}" var="list" varStatus="loop">
   <c:set var="l" value="${loop.index}" />

    <tr>
    <td><c:out value= "${l+1}" /></td>
      <td><c:out value="${list.name}" /></td>
      <td><c:out value="${list.size} MB" /></td>
      <td><c:out value="${list.preview}" /></td>
      <td><i class="material-icons">edit</i>
      <i class="material-icons" onclick="Remove()">delete</i></td>
    </tr>
  </c:forEach>

list.preview contains the byte array "[B@526d24d9"

2 Answers

Create a String previewUrl field in your entity class. and inside the getter write this code .

public String getPreviewUrl() {
        String pu = Base64.encode(getPreview());
        setPreviewUrl(pu);
        return previewUrl;
    }

and in your jsp code ,

<td><img class='imagem_artigo' src='data:image/png;base64,${list.previewUrl}' alt='IMG DESC' width="200" height='200'></td>

This will work

keep in mind, that the data coming from your database is the actual bytes of the image file. What you need to put in your JSP is an tag with a reference to the picture. Additionally, you'll need a controller that just outputs the plain image as response - not embedded in HTML.

For Step 1, your JSP should look something like:

<tr>
  <td><c:out value= "${l+1}" /></td>
  <td><c:out value="${list.name}" /></td>
  <td><c:out value="${list.size} MB" /></td>
  <td><img src="<c:out value="${list.previewUrl}" />"></td>
  <td><i class="material-icons">edit</i>
  <i class="material-icons" onclick="Remove()">delete</i></td>
</tr>

(you'll need to define previewUrl and have it point to a controller that can write out the image data)

In the second step, you'd need to create such a controller that will output the contents of your image byte array to the output stream of the HttpServletResponse.

As a final note: I am a bit confused about the first snippet - are you retrieving the image data from a file or from database? (if the latter is the case, the size of the byte array might be calculated wrongly)

Related