【问题标题】:How to retrieving Image with text from MySQL using Spring + Hibernate如何使用 Spring + Hibernate 从 MySQL 中检索带有文本的图像
【发布时间】:2015-01-28 21:48:31
【问题描述】:

有人可以帮忙吗,我正在尝试使用 Spring MVC + Hibernate 从数据库中检索带有一些文本的图像,但失败得很惨。我可以显示一个或另一个,但不能同时显示(图像和文本),它也在控制台中给我一个错误。 错误:- getOutputStream() has already been called for this response DAO:-

public List<Product> listProductsById(Integer productId) {
    List<Product> prod = em.createNamedQuery("Product.findByProductId")
            .setParameter("productId", productId).getResultList();
    return prod;
}
public byte[] loadImage(Integer productId){
    return em.find(Product.class, productId).getimage();
}

控制器:-

@RequestMapping(value = "details/{id}", method = RequestMethod.GET)
public String showProductDetails(@PathVariable("id") Integer id,
        Model model, HttpServletResponse response) throws IOException {

    List<Product> product = olss.listProductById(id);
          byte[] image = olss.loadImage(id);

           response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
           response.getOutputStream().write(image);
           response.getOutputStream().flush();  
           response.getOutputStream().close();

           model.addAttribute("prodList", product);
           model.addAttribute("prodList", image);

    return "prodDetails";
}

JSP:-

<img alt="Image of product" src="prodDetails?id=${prod.productId}">

【问题讨论】:

  • 在数据库中存储图像可能不是一个好习惯。如果可能,只需将其存储在服务器上并将路径存储在数据库中。

标签: java mysql spring hibernate spring-mvc


【解决方案1】:
   model.addAttribute("prodList", product);
   model.addAttribute("prodList", image);

也许这是您的问题..您将差异值放在同一个键中。

或者你为什么不把你的图片的文件名保存在你的数据库中。See This Link

【讨论】:

    【解决方案2】:

    欢迎来到堆栈溢出(也可能来到 MVC 编程)。您不会以您尝试的方式将模型返回到视图。图像可以以有效的图像格式(如 png、gif、jpg)作为其自己的响应。不是字节数组

    您的图片标签将如下所示:

    然后你需要设置一个单独的控制器函数来返回图像:

    @RequestMapping...
    public @ResponseBody byte[] productLabel(...) {
            byte[] imageByte = new byte[0];
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageIO.write(img, "png", baos);
                baos.flush();
                imageByte = baos.toByteArray();
                baos.close();
            } catch(IOException e) {
                logger.error("Unable to generate Image for Shipping Label on Order "+orderId+". "+
                        e.getLocalizedMessage());
                return null;
            }
            return imageByte;
    }
    

    请注意您的想法是错误的:JSP 是用于生成 HTML 的模板引擎。您不会在 html 页面中嵌入图像,而是定义带有图像路径的图像标记。

    【讨论】:

    • 感谢您的回复,但我仍然不明智。当然有办法将它们显示在一起(图像和文本)。
    • 没有!我已经更新了我的答案,所以希望这可以澄清事情。您的 HTML 页面是一回事,图片标签将向您的服务器发出单独的请求以获取图片。
    • 另外,正如另一位用户所提到的,不要将图像存储在您的数据库中,除非您对此有充分的合理解释。图像应存储在您的文件系统中。
    • 非常感谢我现在正在做的这些帮助,稍后会告诉你。
    • 我刚刚注意到我的问题被否决了为什么?
    猜你喜欢
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    • 2013-06-27
    • 1970-01-01
    • 2015-07-16
    • 2013-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多