开发者

Java EE web-application file creation

开发者 https://www.devze.com 2023-02-11 03:20 出处:网络
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

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:

  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

0

精彩评论

暂无评论...
验证码 换一张
取 消