Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the path to "context path" for uploaded files using Apache Common fileupload?

I'm using Apache common fileupload library with Netbeans 6.8 + Glassfish.I'm trying to change the current upload path to be in the current context path of the servlet , something like this: WEB-INF/upload

so I wrote :

File uploadedFile = new File("WEB-INF/upload/"+fileName);
session.setAttribute("path",uploadedFile.getAbsolutePath());
item.write(uploadedFile);

but I noticed that the library saves the uploaded files into glassfish folder , here what I get when I print the absolute path of the uploaded file :

C:\Program Files\sges-v3\glassfish\domains\domain1\WEB-INF\upload\xx.rar 

My Question :

  • How can I force the common fileupload to save the uploaded file in a path relative to the current servlet path , so I don't need to specify the whole path ? is this possible ?
like image 684
Abdullah Avatar asked Feb 26 '23 23:02

Abdullah


1 Answers

The java.io.File acts on the local disk file system and knows absolutely nothing about the context it is running in. You should not expect it to find the "right" location when you pass a relative web path in. It would become relative to the current working directory which is dependent on how you started the environment. You don't want to be dependent on that.

You can use ServletContext#getRealPath() to convert a relative web path to an absolute local disk file system path.

String relativeWebPath = "/WEB-INF/uploads";
String absoluteFilePath = getServletContext().getRealPath(relativeWebPath);
File uploadedFile = new File(absoluteFilePath, FilenameUtils.getName(item.getName()));
// ...

That said, I hope that you're aware that the deploy folder isn't the right location for uploaded files which are supposed to be saved permanently. Everything will get lost when you redeploy the webapp. See also How to write a file to resource/images folder of the app?

like image 174
BalusC Avatar answered Mar 05 '23 18:03

BalusC