2

I'm trying to obtain a PNG file as InputStream in my managed bean as below:

ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
InputStream input = externalContext.getResourceAsStream("/myFile.png");
// input is null.

However, the InputStream is always null. How is this caused and how can I solve it?

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
Lukas Novicky
  • 878
  • 1
  • 15
  • 41

1 Answers1

6

Apparently you placed the resource in physically the wrong location.

The ExternalContext#getResourceAsStream(), which delegates in case of servlet containers under the covers to ServletContext#getResoruceAsStream(), has its root in the web content of the WAR (the parent folder of /WEB-INF and /META-INF folders, thus the files therein are also available this way), and the /META-INF/resources folder of all JARs in /WEB-INF/lib. In case of a JSF web application it are usually XHTML, CSS, JavaScript and image files.

In other words, it returns web resources. It doesn't return a disk file system resource, for that you need new FileInputStream() instead. It also doesn't return a classpath resource, for that you need ClassLoader#getResourceAsStream() instead. The classpath has its root in a.o. /WEB-INF/classes, all JARs in /WEB-INF/lib, and some VM/server-configured folders depending on the runtime environment.

In an usual web content file structure, the resource file has to be placed exactly here in order to obtain it the desired way:

WebContent
 |-- META-INF
 |-- WEB-INF
 |    |-- faces-config.xml
 |    `-- web.xml
 |-- myFile.png    <-- Here.
 :
Community
  • 1
  • 1
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452