1

I am working on a Spring-MVC application and I must use image upload for storing images in Database. I tried to go through examples on internet, but my overall observation is there is some argument regarding type of upload, and who manages it. Nevertheless, I am uploading the image from an HTML, saving it in Database as OID, using byte array with @Lob to save. I am unable to see the image preview when i use :

I will post code of how I have achieved it, kindly let me know whats wrong.

HTML code for image preview :

 <img src="${product.productimage}" width="100" height="100"/>

When I use product.getImage().toString in service, I get weird characters by 'B[jlkisf12', but only 12-13 of them, I imagine that is the path.

Entity :

@Column(name = "productimage")
byte[] productimage;  // With getters and setters

JSP file :

   <c:url var="add" value="/product/add"></c:url>
<form:form action="${add}" commandName="product">
    <table>
        <c:if test="${!empty product.productname}">
            <tr>
                <td>
                    <form:label path="productid">
                        <spring:message text="productid"/>
                    </form:label>
                </td>
                <td>
                    <form:input path="productid" readonly="true" size="8"  disabled="true" />
                    <form:hidden path="productid" />
                </td>
            </tr>
        </c:if>

        <tr>
            <td>
                <form:label path="productname">
                    <spring:message text="productname:"/>
                </form:label>
            </td>
            <td>
                <form:input path="productname"/>
            </td>
        </tr>
        <tr>
            <td>
                <form:label path="productdescription">
                    <spring:message text="productdescription"/>
                </form:label>
            </td>
            <td>
                <form:input path="productdescription"/>
            </td>
        </tr>
        <tr>
            <td>
                <form:label path="productcondition">
                    <spring:message text="productcondition"/>
                </form:label>
            </td>
            <td>
                <form:input path="productcondition"/>

            </td>
        </tr>
        <tr>
            <td>
                <form:label path="productage">
                    <spring:message text="productage"/>
                </form:label>
            </td>
            <td>
                <form:input path="productage" />
            </td>
        </tr>
        <tr>
            <td>
                <form:label path="productean">
                    <spring:message text="productean"/>
                </form:label>
            </td>
            <td>
                <form:input path="productean" />
            </td>
        </tr>

        <tr>
            <td>
                <form:label path="productisbn">
                    <spring:message text="productisbn"/>
                </form:label>
            </td>
            <td>
                <form:input path="productisbn" />
            </td>
        </tr>

        <tr>
            <td>
                <form:label path="ordernumber">
                    <spring:message text="ordernumber"/>
                </form:label>
            </td>
            <td>
                <form:input path="ordernumber" />
            </td>
        </tr>

        <tr>
            <td>
                <form:label path="productimage">
                    <spring:message text="productimage"/>
                </form:label>
            </td>
            <td>
                <form:input type="file" path="productimage" />
            </td>
        </tr>



    </table>
    <tr>
        <td colspan="2">
            <c:if test="${!empty product.productname}">
                <input type="submit"
                       value="<spring:message text="Edit Product"/>" />
            </c:if>
            <c:if test="${empty product.productname}">
                <input type="submit"
                       value="<spring:message text="Add Product"/>" />
            </c:if>
        </td>
    </tr>
</form:form>

<br>
<h3>Product List</h3>
<c:if test="${!empty listProducts}">
    <table class="tg">
        <tr>
            <th width="80">Product ID</th>
            <th width="80">Product image</th>
            <th width="120">Product name</th>
            <th width="120">Product description</th>
            <th width="120">Product condition</th>
            <th width="120">Product age</th>
            <th width="120">Product EAN</th>
            <th width="120">Product ISBN</th>
            <th width="120">Product ordernumber</th>
            <th width="120">Product owners id</th>

            <th width="60">Edit</th>
            <th width="60">Delete</th>
        </tr>

        <c:forEach items="${listProducts}" var="product">
            <tr>
                <td>${product.productid}</td>
                <td>${product.productimage} </td>
                <td>${product.productname}</td>
                <td>${product.productdescription}</td>
                <td>${product.productcondition}</td>
                <td>${product.productage}</td>
                <td>${product.productean}</td>
                <td>${product.productisbn}</td>
                <td>${product.ordernumber}</td>
                <td>${product.user1id}</td>
          <img src="${image}" width="100" height="100"/> //image not found
                <td><a href="<c:url value='/editproduct/${product.productid}' />" >Edit Product</a></td>
                <td><a href="<c:url value='/removeproduct/${product.productid}' />" >Delete Product</a></td>
            </tr>
            <img src="${product.saveimage}" height="100" width="100">
        </c:forEach>


    </table>
</c:if>

Controller :

     @RequestMapping(value="/product/show",method= RequestMethod.GET)
     public String listProducts(@ModelAttribute("product") ProductBasic productBasic,Model model)   {
     User user = userService.getCurrentlyAuthenticatedUser();
     model.addAttribute("product", new ProductBasic());
     model.addAttribute("listProducts",this.productBasicService.listProduct(user));
     BASE64Encoder base64Encoder = new BASE64Encoder();
     StringBuilder stringBuilder = new StringBuilder();
     stringBuilder.append("data:image/png;base64,");
     stringBuilder.append(base64Encoder.encode(productBasic.getProductimage())); 
     String image = stringBuilder.toString();
     model.addAttribute("saveimage",image);
     return "product";
 }

@RequestMapping(value="/product/add")
public String addProduct(@ModelAttribute("product") ProductBasic productBasic,Model model){
    User user = userService.getCurrentlyAuthenticatedUser();
    model.addAttribute("product", new ProductBasic());
    productBasicService.addProduct(user,productBasic);
    return "redirect:/product/show";
}
  @RequestMapping("/removeproduct/{id}")
    public String removeProduct(@PathVariable("id") int productid,Model model) {
        User user = userService.getCurrentlyAuthenticatedUser();
        model.addAttribute("listProducts",this.productBasicService.listProduct(user));
        this.productBasicService.removeProduct(productid,user);
        return "redirect:/product/show";
    }

    @RequestMapping("/editproduct/{id}")
    public String updateProduct(@ModelAttribute("product") ProductBasic productBasic,@PathVariable("id") Integer id,Model model){
        User user = userService.getCurrentlyAuthenticatedUser();
        model.addAttribute("product", this.productBasicService.getProductById(id));
        model.addAttribute("listProducts",this.productBasicService.listProduct(user));
        return "product";
    }

NullPointerException:

java.lang.NullPointerException
    java.io.ByteArrayInputStream.<init>(ByteArrayInputStream.java:106)
    sun.misc.CharacterEncoder.encode(CharacterEncoder.java:188)
    com.WirTauschen.UserController.listProducts(UserController.java:67)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:606)
    org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)

What am I doing wrong? Kindly let me know.

2
  • p.getImage().toString returns Image is[B@54b65954 Commented Nov 17, 2014 at 14:59
  • Well, what's actually in the DB? Commented Nov 18, 2014 at 4:22

1 Answer 1

2

In your Controller or method add below code for image

    BASE64Encoder base64Encoder = new BASE64Encoder();
    StringBuilder imageString = new StringBuilder();
    imageString.append("data:image/png;base64,");
    imageString.append(base64Encoder.encode(bytes)); //bytes will be image byte[] come from DB 
    String image = imageString.toString();
    modelView.put("imagetoDisplay",image);// put in your model object for using in your JSP

And in your JSP

  <img src="${imagetoDisplay}" width="100" height="100"/>
Sign up to request clarification or add additional context in comments.

15 Comments

Sorry for late reply, I was in meeting.Hello Pravin, I am adding only 1 image right now for testing, later I have to add multiple images. I can use something which is more dynamic. Plus, when I try to use <img src> tag anywhere in the product.jsp file, it cannot find the contents within the $ bracket.
Above code will works fine with dynamic behavior.. If you fetching image directly from DB it will returns you byte[] you need to encode that byte[] using base64 ... have you tried above ?? and ${} should work .. can you share error or something
The ${} does not work,it says not found image. Can you please check the post I have edited.
you have done coding for image in @RequestMapping(value="/product/add") this URL is might call after you submit the page/form .. According to me you should write that code in @RequestMapping(value="/product/show",method= RequestMethod.GET) or the method from whom above jsp is returned
You are correct, I just changed it to /product/show. KIndly check the updated post. I am getting NullPointerException because of that. Error code is in post.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.