简体   繁体   中英

request.getServletContext().getRealPath(); is returning my target directory instead of src?

I am trying to implement a feature on my site that saves files to a project directory. Here is the method that is doing it.

 @RequestMapping(value = "/upload", method = RequestMethod.POST)
public String Upload(@RequestParam("file") MultipartFile file, Principal principal, HttpServletRequest request) throws IOException {
    if (!file.isEmpty()) {

                String uploadsDir = "/uploads/";
                String realPathtoUploads =  request.getServletContext().getRealPath(uploadsDir);
                if(! new File(realPathtoUploads).exists())
                {
                    new File(realPathtoUploads).mkdir();
                }


                String orgName = file.getOriginalFilename();
                String filePath = realPathtoUploads + orgName;
                File dest = new File(filePath);
                file.transferTo(dest);


        return "user";
    }
    return "user";

}  

It is saving the file but it is saving in the target directory. Shouldn't I be saving files to my src directory and not my target? How can I change it so its going to the src direct? Thanks!

I am using netbeans btw if that makes any difference.

All path related methods actually calculate the path based on the folder the container launched your app from. So if you launched your Tomcat or Jetty or another container using probably maven, your application was launched from the target folder which is where maven places the war and all other resources.

Hence, getRealPath actually takes the application location and concatenates the relative "/uploads" to it.

Of course your container behaves as it should.

Your requirement is achievable, however if you choose to manipulate the path yourself than any change to the folder location would force to change it manually.

You could do for example :

String rootPath = "/home/user/";
String downlods = "downloads";

String realPathtoUploads = rootPath + downlods ;

if(! new File(realPathtoUploads).exists()) {
  new File(realPathtoUploads).mkdir();
}

HTH, Gal

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM