Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to provide relative path in File class to upload any file? [duplicate]

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());
like image 219
AabinGunz Avatar asked May 19 '11 13:05

AabinGunz


1 Answers

I want to provide a relative path

Never do that in a webapp. The working directory is not controllable from inside the code.


because the program should work in both linux and windows env.

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.

File file = new File("/path/to/uploaded/files", filename);
// ...

This is what i am using to upload

 realPath = getServletContext().getRealPath(/files);
 destinationDir = new File(realPath);

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:

  • getResourceAsStream() vs FileInputStream
  • Best Location for Uploading file
  • Simplest way to serve static data from outside the application server in a Java web application
like image 123
BalusC Avatar answered Sep 24 '22 20:09

BalusC