I'm developing a web application in java to control my stock and do some other things. I upload files through a JSF component. This file开发者_StackOverflow社区s are images. Anyway, my question is, I want these images to be stored in the web application's resource folder. More specifically in a subfolder named "userUploads". I create a File object but how do I a get a String representing that path?
If you want your files to be stored in your "web application's resource folder" I'm guessing you mean a folder called 'resources' inside the 'webroot'. While this is not really the best approach, you can achieve this by using the ServletContext
:
ServletContext sc = httpRequest.getSession().getServletContext();
String path = sc.getPath("resources");
or
File file = new File(sc.getPath("resources"))
Personally, I'd recommend creating your 'uploads' folder outside of your web app's directory, so that it is not replaced during deployment etc.
"I create a File object but how do I a get a String representing that path?"
If you have a File
object, you can call myFile.getAbsolutePath()
to get a string representation of the path.
Do the following:
- Get the
HttpSession
from theHttpServletRequest
. - Get the
ServletContext
from theHttpSession
. - Get the absolute path to your installation using the
ServletContext.getRealPath()
method. The parameter to this method is a path that is relative to your context root.
Here is a link: ServletContext
精彩评论