【问题标题】:Image upload using Hibernate inside PostgreSQL在 PostgreSQL 中使用 Hibernate 上传图像
【发布时间】:2015-01-14 12:32:54
【问题描述】:

我正在开发一个 Spring-MVC 应用程序,我必须使用图像上传来将图像存储在数据库中。我尝试浏览互联网上的示例,但我的总体观察是关于上传类型以及谁管理它存在一些争论。不过,我正在从 HTML 上传图像,将其作为 OID 保存在数据库中,使用带有 @Lob 的字节数组进行保存。我使用时看不到图像预览:

我将发布我如何实现它的代码,请告诉我有什么问题。

图片预览的HTML代码:

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

当我在服务中使用 product.getImage().toString 时,我得到了 'B[jlkisf12' 的奇怪字符,但我想只有 12-13 个字符。

实体:

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

JSP 文件:

   <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>

控制器:

     @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";
    }

空指针异常:

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)

我做错了什么?请告诉我。

【问题讨论】:

  • p.getImage().toString 返回 Image is[B@54b65954
  • 嗯,究竟是什么在数据库中

标签: spring hibernate postgresql


【解决方案1】:

在您的控制器或方法中添加以下图像代码

    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

在你的 JSP 中

  <img src="${imagetoDisplay}" width="100" height="100"/>

【讨论】:

  • 抱歉回复晚了,我正在开会。你好 Pravin,我现在只添加 1 张图片进行测试,稍后我必须添加多张图片。我可以使用更动态的东西。另外,当我尝试在 product.jsp 文件中的任何位置使用 标记时,它找不到 $ 括号内的内容。
  • 以上代码可以很好地处理动态行为。如果您直接从数据库中获取图像,它将返回字节[],您需要使用 base64 对该字节[] 进行编码...您在上面尝试过吗? ?并且 ${} 应该可以工作..你能分享错误或其他东西吗
  • ${} 不起作用,它说找不到图像。你能检查一下我编辑过的帖子吗?
  • 您已经在@RequestMapping(value="/product/add") 中完成了图像编码,在您提交页面/表单后可能会调用此 URL .. 根据我的说法,您应该在 @RequestMapping(value="/product/show",method= RequestMethod.GET) 或上面的方法中编写该代码返回jsp
  • 你说得对,我只是把它改成了/product/show。请检查更新的帖子。因此,我得到了 NullPointerException。错误代码在帖子中。
猜你喜欢
  • 2018-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-25
  • 2018-11-27
  • 2011-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多