It is doable but, as Dmitry said, it might not work on every server. SecurityManager
class should be consulted if your webapp has the privilege to write to that folder. or you will get an exception.
One way to do it is via ServletContext
:
URL webAppRoot = this.getServletConfig().getServletContext()
.getResource("/images/new-image.jpg");
This will point to your ${tomcat}/webapps/mywebapp/images/new-image.jpg
.
Another way is via ProtectionDomain
:
URL runningClassLocation = this.getClass().getProtectionDomain()
.getCodeSource().getLocation();
But this will most likely give you jar:file://...myapp.jar!/my/package/servlet.class
.
After you have the URL you convert it to File
and append any relative path to your image folder.
UPDATE:
I agree with Jim, and emphasize that doing it like this is just for academic purposes.
Java is not like PHP so you shouldn't have uploads
folder inside your web application's folder. Usually this is done by enabling an administrator-level user to specify a file path to a folder reserved for your application's storage needs.