简体   繁体   中英

Java EE web-application file creation

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 files 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:

  1. Get the HttpSession from the HttpServletRequest .
  2. Get the ServletContext from the HttpSession .
  3. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM