Spring MVC:如何在控制器中获取文件路径?

6
我有以下文件夹结构:
ProjectFolder/images/some images

在同一个文件夹中

ProjectFolder/WEB-INF/classes/com/xyz/here is java file of controller.

我该如何在控制器中获取图片路径?

请帮忙,谢谢 :)


为什么你不能只使用/images/some images - adarshr
我尝试了相同的操作,但出现了文件未找到的异常。 - Sachin J
FileInputStream inputStream = new FileInputStream("/images/abort.png"); - Sachin J
这样行不通。您不能在 Web 上下文中使用 FileInputStream。请从其他地方获取另一个流。 - adarshr
2个回答

10
如果是一个Web环境,可能像这样的东西会有所帮助。
InputStream is = null ;
is = request.getSession().getServletContext().getResourceAsStream("/images/someimage.jpg");

或者可能是像这样的:

InputStream is = null ;
String realPath  = request.getSession().getServletContext().getRealPath("/images/someimage.jpg");
is = new FileInputStream(realPath);

0

你可以将图片路径存储在属性文件中。

将该属性文件存储在类路径中。

现在可以在控制器类中像这样访问该属性:

Properties properties = new Properties();
/*to access your filename.properties file */
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("filename.properties"));

String  sServerLocation = properties.getProperty("server.upload.docs.path");

请注意,在您的属性文件中应使用转义字符,例如:

server.upload.docs.path=D:\\JDIS3\\DOCS\\

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接