如何获取公共网站内容资源的InputStream? [英] How to obtain an InputStream of a public webcontent resource?

查看:61
本文介绍了如何获取公共网站内容资源的InputStream?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在WAR中打包了一组图像,并使用<p:graphicImage><p:dataGrid>中对其进行了描绘.图像位于/resources/icons文件夹中.我希望能够选择一个图像并将该图像的副本保存到提交时的磁盘上.

I have a collection of images packaged in my WAR and I depict them in a <p:dataGrid> using <p:graphicImage>. The images are located in the /resources/icons folder. I want to be able to select an image and save a copy of this image to disk on submit.

这怎么办?如何获得对此图像的引用(InputStream或其他内容)?

How can this be done? How can I get a reference (InputStream or whatever) to this image?

推荐答案

给出此文件夹结构,


YourProject
 |-- src
 |    `-- com
 |         `-- example
 |              `-- BackingBean.java
 |-- WebContent
 |    |-- META-INF
 |    |-- WEB-INF
 |    |-- resources
 |    |    `-- icons
 |    |         `-- foo.png
 |    `-- foo.xhtml
 :

您可以通过 ExternalContext#getResourceAsStream() ,它采用相对于webcontent的路径:

You can get it by either ExternalContext#getResourceAsStream() which takes webcontent-relative path:

ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
InputStream input = externalContext.getResourceAsStream("/resources/icons/foo.png");
// ...

或通过 Resource#getInputStream() ,其中Resource是从

Or by Resource#getInputStream() wherein Resource is obtained from ResourceHandler#createResource() which takes a /resources-relative path:

ResourceHandler resourceHandler = FacesContext.getCurrentInstance().getApplication().getResourceHandler();
InputStream input = resourceHandler.createResource("icons/foo.png").getInputStream();
// ...

关于选择图像并传递其路径,只需执行以下操作:

As to selecting the image and passing its path around, just do something like as follows:

<h:graphicImage name="icons/foo.png">
    <f:ajax event="click" listener="#{bean.setImage(component.name)}" />
</h:graphicImage>
<h:graphicImage name="icons/bar.png">
    <f:ajax event="click" listener="#{bean.setImage(component.name)}" />
</h:graphicImage>
<h:commandButton value="submit" action="#{bean.saveImage}" />

另请参见:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆