Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

java - How to obtain an InputStream of a public webcontent resource?

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Given this folder structure,

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

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");
// ...

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}" />

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...