java - 如何从 JSF/Webflow 应用程序提供二进制内容?

标签 java jsf streaming spring-webflow

我有一个 JSF 1.2/Spring Web flow 2.0.7 应用程序,需要提供二进制内容(图像)。该内容作为 Base64 编码字符串从 Web 服务(以及一些其他数据)获取,并最终与其余数据一起出现在 bean 中。如何让图像显示在我的网页上?

注意:不,没有办法让 Web 服务直接传输数据,甚至无法从 Web 服务中获取二进制数据而无需其他任何东西。

最佳答案

您希望最终在 <h:graphicImage> 中得到该图像组件,对吗?理论上,您可以使用 data URI format为此。

<h:graphicImage value="data:image/png;base64,#{bean.base64Image}" />

但是,您会遇到一个问题,即它无法在所有当前浏览器上运行。例如,MSIE 限制 data 的长度URI 为 32KB。

如果这些图像通常较大,或者您也想支持过时的浏览器,那么您当前最好的选择就是让它指向一个完整的 URL。毕竟

<h:graphicImage value="images/filename.png" />

有两种方法可以使其发挥作用:

  1. 将图像临时写入公共(public)网络内容并以通常的方式引用它。

    this.uniqueImageFileName = getOrGenerateItSomehow();
    byte[] imageContent = convertBase64ToByteArraySomehow();
    ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
    ServletContext sc = (ServletContext) ec.getContext();
    File image = new File(sc.getRealPath("/images"), uniqueImageFileName);
    // Write byte[] to FileOutputStream on that file the usual way (and close!)
    

    并按如下方式使用它:

    <h:graphicImage value="images/#{bean.uniqueImageFileName}" />
    

    但是,只有当 WAR 已扩展并且您拥有磁盘文件系统的写入权限时,这才有效。您还需要考虑清理工作。一个HttpSessionListener可能对此有所帮助。

  2. 将二进制数据存储在 session 中并具有 HttpServlet来提供它。假设您的 bean 属于请求范围:

    this.uniqueImageFileName = getOrGenerateItSomehow();
    byte[] imageContent = convertBase64ToByteArraySomehow();
    ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
    ec.getSessionMap().put(uniqueImageFileName, imageContent);
    

    View 如下所示:

    <h:graphicImage value="images/#{bean.uniqueImageFileName}" />
    

    创建 HttpServlet映射到 url-pattern/images/*并且像 doGet() 中的以下内容一样方法:

    String uniqueImageFileName = request.getPathInfo().substring(1);
    byte[] imageContent = (byte[]) request.getSession().getAttribute(uniqueImageFileName);
    response.setContentType("image/png"); // Assuming it's always PNG.
    response.setContentLength(imageContent.length);
    // Write byte[] to response.getOutputStream() the usual way. 
    

关于java - 如何从 JSF/Webflow 应用程序提供二进制内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4133982/

相关文章:

java - 在哪里可以找到 Java API 代码

javascript - 调用 f :selectitems 的 Javascript 函数 onchange

html - 如何在 JSF 页面上显示 PDF

jsf - p :fileUpload doesn't work inside p:dialog

使用 XProc 进行 XML 流式处理

android - Android 应用程序中 VideoView 中的 RTSP 流

python - BigQuery 拒绝在流式传输时插入少量记录

java - 将 Spring Boot 应用程序作为 jar 执行会给出 "no main manifest attribute"

java - 不同包的子类继承?

java - 如何按升序对集合中的元素进行排序?