【问题标题】:Spring + JSF - Retrieve Image from Database and Show in Brower [duplicate]Spring + JSF - 从数据库中检索图像并在浏览器中显示 [重复]
【发布时间】:2017-07-13 08:00:40
【问题描述】:

我正在使用 Spring 4 + JSF 2.0 框架 + MySQL 数据库开发一个网站。 我正在尝试从数据库中检索图像并将其显示在浏览器上。 所以基本上我有一个名为 product_t 的表,其中有一个名为 image 的 LongBlob 列,它负责存储 png 文件。

我需要从页面中的每个产品中检索每个图像,所以:

<ui:repeat value="#{productControllerImpl.list3NotNewRandomProducts()} var="product" varStatus="status">
<h2>#{product.name}</h2>
<strong>#{product.subDescription}</strong><br></br> <span>#{product.description}
</ui:repeat>

到目前为止一切顺利。

我在谷歌上搜索以下解决方案:

对于 UI 中的每个产品,我需要调用一个 Servlet 来检索图像。 由于我使用的是 JSF + Spring,所以我在 UI 中编写了以下代码块:

<h:graphicImage   value="/images/#{productControllerImpl.findProductImageById(product.id)}"/>

在我的 productControllerImpl 我有这个:

@Override
public byte[] findProductImageById(Long productId) {
    byte[] productImage = null;
    HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();      
    ServletOutputStream outputStream = null; 
    try {
        productImage = productService.findProductImageById(productId);
        response.reset();           
        outputStream = response.getOutputStream();
        response.setContentType("image/png");
        outputStream.write(productImage);
        outputStream.flush();       
        outputStream.close();
    } catch(Throwable e){
        throw new RuntimeException("Error processing product image: " + e.getMessage(), e);
    }

    return null;
}

所以基本上我从迭代中接收到 producIt,并在数据库中搜索相应的产品图像(我不知道这是否是最佳选择)。

这里的问题是,当访问此页面时,我会在浏览器中收到完整的图像:

我很迷失在这部分。

有人知道我在这里缺少什么吗?

提前致谢。

【问题讨论】:

    标签: java mysql spring image jsf-2


    【解决方案1】:

    我假设你指的是Show image as byte[] from database as graphic image in JSF page

    我相信您的主要问题是您要结束响应流: outputStream.flush();
    outputStream.close(); 删除它们,然后在 doGet 上为图像 servlet 重试。

    我个人更喜欢带有 PrimeFaces 的 StreamedContent,正如这里提到的 Display dynamic image from database with p:graphicImage and StreamedContent

    或 OmniFaces graphicsImage http://showcase.omnifaces.org/components/graphicImage 而不是创建 servlet 来输出内容。

    BalusC 的这篇文章将解决你所有的问题:Servlet for serving static content

    【讨论】:

    • 你好 VeernarM。感谢你的帮助。我试图删除 outputStream.flush(); outputStream.close();然而结果是一样的。 =(对于StreamedContent,它是一个PrimeFaces库,我的应用程序将非常繁重,所有这些primefaces库只是为了显示图像。我尝试使用OminiFaces,但它只适用于Java CDI。=(为什么我的图像会重新渲染浏览器全屏?
    • 您需要添加更多要查看的 xhtml 页面,因为它可能是 CSS/页面错误,与您的 servlet 无关。
    • 我可以通过以下方法解决这个问题:我将 Apache Commons Codec 依赖项添加到我的项目中。并在 DTO 中添加了 Base64.encodeBase64String 返回的字符串: productDTO.setImage(Base64.encodeBase64String(productT.getImage())); productT.getImage() 返回一个 byte[],它是来自数据库的 blob 数据。在我的 xhtml 中,我添加了以下标签: (它也适用于 标签)。于是问题就解决了!谢谢大家,希望这个解决方案能帮助其他有同样问题的开发者。 =)
    猜你喜欢
    • 2014-04-04
    • 1970-01-01
    • 2015-01-01
    • 2020-10-15
    • 1970-01-01
    • 2014-09-22
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多