ExternalContext#getResourceAsStream() returns null, where to place the resource file?
Asked Answered
B

1

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?

Boob answered 11/9, 2014 at 9:59 Comment(1)
May help you stackoverflow.com/questions/3160691/…Blowy
H
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.
 :
Heliogravure answered 6/3, 2015 at 8:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.