This question already has an answer here:
I am uploading a file, for which I want to provide a relative path, because the program should work in both linux and windows env.
This is what I am using to upload
realPath = getServletContext().getRealPath(/files);
destinationDir = new File(realPath);
if(!item.isFormField())
{
File file = new File(destinationDir,item.getName());
item.write(file);
}
Any other means to directly provide relative path here
File file = new File(destinationDir,item.getName());
As BalusC points out, you do not want to save files to a destination found with getRealPath. Not only will such files be wiped out when you redeploy, but they will also be available for download by any user who can reach your web site, which, depending on what you're up to, may be a serious security problem.
When I'm faced with this problem, I normally create a properties file, and put the directory in which to save the files in the properties file. Then I can have a different path for Linux and Windows, or for server A and server B. It may work for you to just invent a path and hardcode it, but I often find that I need different paths on different servers. Like, in my present project we have three instances of Tomcat running on the same physical box for different stages of testing. We don't want files they write to all go to the same directory: each should have its own.
Never do that in a webapp. The working directory is not controllable from inside the code.
Just use
"/path/to/uploaded/files"
. It works equally in both environments. In Windows it will only be the same disk as where the server runs.You should not store the files in the webcontent. This will fail when the WAR is not expanded and even when it is, all files will get lost whenever you redeploy the WAR. Store them outside the WAR in an absolute location, e.g.
/path/to/uploaded/files
as suggested before.See also: