bablu
bablu

Reputation: 611

How to display image from mysql database using spring mvc

I am storing BLOB type image in MySQL database using Spring MVC for item class Item (itemId, itemName, itemPrice, itemContent, itemImage). I successfully stored image in database but when I'm trying to display it in my jsp, it is showing something binary like [B@7fb0c025.

How can I display proper image in JSP (image is stored in MySQL database table)

My model class:

@Entity
@Table(name="item")
public class Item {

@Id
@Column(name="ItemId")
@GeneratedValue
private Integer itemId;

@Column(name="ItemName")
private String itemName;

@Column(name="ItemContent")
private String itemContent;
/*
@Column(name="ItemImage")
private ByteArray ItemImage;
*/
@Column(name="ItemPrice")
private int itemPrice;

@Column(name="ItemImage")
private byte[] itemImage;

"addItem.jsp" to add item attributes along with the image in database.

<form:form modelAttribute="itemAttribute" enctype="multipart/form-data" method="POST" action="${Url}">
<table>

    <tr>
        <td><form:label path="itemId"></form:label></td>
        <td><form:input path="itemId" type="hidden"/></td>
    </tr>

    <tr>
        <td><form:label path="itemName">ItemName:</form:label></td>
        <td><form:input path="itemName"/></td>
    </tr>
    <tr>
        <td><form:label path="itemPrice">ItemPrice:</form:label></td>
        <td><form:input path="itemPrice"/></td>
    </tr>
    <tr>
        <td><form:label path="itemContent">ItemContent:</form:label>
        <td><form:input path="itemContent"/>
    </tr>
    <tr>
        <form:label for="itemImage" path="itemImage">itemImage:</form:label>
        <form:input path="itemImage" type="file" />
    </tr>
</table>

<input type="submit" value="Save" />
</form:form>

The JSP page to display item attributes along with the image. CategoryId:

    <tr>
        <td><form:label path="categoryName">CategoryName:</form:label></td>
        <td><form:input path="categoryName"/></td>
    </tr>
</table>
<input type="submit" value="Save" />

<table width: 100%; text-align:center">
<tr>
    <th>ItemId</th>
    <th>ItemName</th>
    <th>ItemPrice</th>
    <th>ItemFeatures</th> 
    <th>Edit</th>
    <th>Delete</th>
    <th>ItemImage</th>
</tr>
<tbody>


    <c:forEach items="${categoryAttribute.item}" var="item">
    <tr>
            <c:url var="editCUrl" value="/item/edit?bid=${categoryAttribute.categoryId}&cid=${item.itemId}" />
            <c:url var="deleteCUrl" value="/item/delete?id=${item.itemId}" />
            <td><c:out value="${item.itemId}" /></td>
            <td><c:out value="${item.itemName}"/></td>
            <td><c:out value="${item.itemPrice}"/></td>
            <td><c:out value="${item.itemContent}"/></td>
            <td><a href="${editCUrl}">EditItem</a></td>
            <td><a href="${deleteCUrl}">DeleteItem</a></td>
            <td><c:out value="${item.itemImage}"/></td>
    </tr>   
    </c:forEach>

How can I properly display the image which is stored in the database? I guess I'm doing it wrong by displaying image like this in JSP. But how can I display the image here in JSP?

Upvotes: 13

Views: 40362

Answers (4)

Devraj Giri
Devraj Giri

Reputation: 21

However, i was using native query to get the ArrayList<> so i could not use setter and getter method in my controller to obtain the bytes to encode to Base64, instead i created a @Transient field in my Dao class to do encode to base64 and it worked.

In my dao

    @Transient
private String imgUtility;


//getter method for encoding
public String getImgUtility() throws UnsupportedEncodingException {

    byte[] encodeBase64 = Base64.encodeBase64(getImage());
     String base64Encoded = new String(encodeBase64, "UTF-8");              
    return base64Encoded;
}

and in the jsp view you can do this

<img src="data:image/jpeg;base64,${tempCust.imgUtility}"/>

Upvotes: 0

Musaddique
Musaddique

Reputation: 443

I wrote below code in my controller and it's working fine for me.

In my project, User contain Profile Object which has photo @Lob. Modify this code as per your attributes.

    byte[] encodeBase64 = Base64.encode(user.getProfile().getPhoto());
    String base64Encoded = new String(encodeBase64, "UTF-8");
    mav.addObject("userImage", base64Encoded );

In JSP file, I wrote code

<img src="data:image/jpeg;base64,${userImage}" />

For this, you require common-codec jar.

Also, you can use a custom tag for showing image.

Upvotes: 8

Musaddique
Musaddique

Reputation: 443

One more thing you can do for displaying the image in jsp from database. suppose you need to display images of all user in jsp. for this you can create your own custome jstl tag which contain code for converting byte image to base64 image.

here in my project the image is in Profile class

i.e user.getProfile().getPhoto()

    package com.spring.tags;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.codec.base64.Base64;

public class UserImage extends SimpleTagSupport {

    private byte[] usrImage;

    public void setUsrImage(byte[] usrImage) {
        this.usrImage = usrImage;
    }

@Override
    public void doTag() throws JspException, IOException {
        System.out.println("tag lib");
        try {
            JspWriter out = getJspContext().getOut();
            if (usrImage != null && usrImage.length > 0) {
                byte[] encodeBase64 = Base64.encode(usrImage);
                String base64Encoded = new String(encodeBase64, "UTF-8");
                out.print("data:image/jpeg;base64,"+base64Encoded);

            }
        } catch (Exception e) {
            throw new JspException("Error: " + e.getMessage());     }
    }   
}

create tld file in WebContent. i have create file in my taglib folder

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd">
  <tlib-version>1.0</tlib-version>
    <short-name>ui</short-name>
    <uri>/taglib/userimage</uri>
    <tag>
        <name>image</name>
        <tag-class>com.spring.tags.UserImage</tag-class>
        <body-content>empty</body-content>
        <info>This Tag Displayes current user profile image</info>
        <attribute>
            <name>usrImage</name>
            <required>true</required>
            <description>Provide a display format</description>
            <rtexprvalue>true</rtexprvalue>
        </attribute>
    </tag>
</taglib>

Now you can write code in jsp for displaying image.

<img src="<ui:image usrImage='${user.profile.photo}' />

Every time no need to convert image in controller just pass byte image to jsp and our custome tag will convert byte image and dispay it in view page.

Note: include custome tag file in jsp file

<%@ taglib uri="/taglib/userimage.tld" prefix="ui"%>

Upvotes: 1

bablu
bablu

Reputation: 611

I'm finally able to display the image on my jsp. what i did.

I separately created a controller like this.

@Controller
@RequestMapping("/myImage")
public class ImageController {

@Resource(name="categoryService")
private CategoryService categoryService;

@Resource(name="itemService")
private ItemService itemService;

@RequestMapping(value = "/imageDisplay", method = RequestMethod.GET)
  public void showImage(@RequestParam("id") Integer itemId, HttpServletResponse response,HttpServletRequest request) 
          throws ServletException, IOException{


    Item item = itemService.get(itemId);        
    response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
    response.getOutputStream().write(item.getItemImage());


    response.getOutputStream().close();

and in the jsp i did this

<img src="/Project1/myImage/imageDisplay?id=${item.itemId}"/>

And the image was successfully displayed.

Upvotes: 31

Related Questions