从doPost()方法访问保存在Servlet的WEB-INF文件夹中的静态文件

时间:2015-05-18 12:44:11

标签: image google-app-engine servlets blob

我尝试访问src/main/webapp/WEB-INF/imgs文件夹中保存在Servlet中的一些图像,这样: link

我尝试使用此代码在doPost的{​​{1}}方法中访问这些图片:

Servlet

InputStream s = this.getClass().getClassLoader().getResourceAsStream("http://cardimgs.org/imgs/cardbackground1.jpg"); Movie movie = new Movie(); try { byte[] bytes = IOUtils.toByteArray(s); movie.setImage(bytes); } catch (IOException e) { e.printStackTrace(); } PersistenceManager pm = PMF.get().getPersistenceManager(); try { // Store the image in App Engine's datastore pm.makePersistent(movie); } finally { pm.close(); } 课程: link 2

我使用指定的Movie创建url的原因是因为我的InputStream我有:

appengine-web.xml

我尝试定义静态文件。

我的问题,但是,通过上述代码,我无法访问我的文件并填写<?xml version="1.0" encoding="utf-8"?> <appengine-web-app xmlns="http://appengine.google.com/ns/1.0"> <application>myApplicationId</application> <version>1</version> <threadsafe>true</threadsafe> <system-properties> <property name="java.util.logging.config.file" value="WEB-INF/logging.properties" /> </system-properties> <static-files> <include path="/**.jpg"/> <include path="/imgs" > <http-header name="Access-Control-Allow-Origin" value="http://cardimgs.org" /> </include> </static-files> </appengine-web-app> ,因此显示为InputStream,因此返回null

如何成功访问我的静态文件?

1 个答案:

答案 0 :(得分:1)

ClassLoader.getResourceAsStream()使用*类加载器**加载资源。因此,它在类路径中查找它们。 Web应用程序的类路径由WEB-INF/classesWEB-INF/lib内的所有jar组成。它期望的路径看起来像com / mycompany / myproject / somefile.txt。它不能是HTTP URL。

您需要的是ServletContext.getResourceAsStream("/WEB-INF/imgs/cardbackground1.jpg")。此方法从Web应用程序内的任何位置加载资源。