12

I am trying to write an uploaded multipart file to the filesystem. I have a directory called audio which sits in the root of my web application (not inside WEB-INF, but beside it, to it's publicly accessible like css and javascript).

I want to write the uploaded file to that directory but I can't seem to get the path I need. I thought getting a ServletContext() then using realPath() may work, but I don't have a reference to ServletContext through a Spring controller. Thanks for any hep

@RequestMapping(value="/uploadSample")
public ModelAndView upload(HttpServletRequest request, HttpServletResponse response, @RequestParam("file") MultipartFile f) {

    if (f == null) {
        return new ModelAndView("upload", "msg", "The file is null.");
    }
    try {
        // I need to set AUDIO_PATH to <webAppRoot>/audio
        FileOutputStream file = new FileOutputStream(AUDIO_PATH + "/" + f.getOriginalFilename());
        file.write(f.getBytes());
        file.close();
    }
    catch (FileNotFoundException ex) {
        Logger.getLogger(SampleUploadController.class.getName()).log(Level.SEVERE, null, ex);
    }
    catch (IOException ex) {
            Logger.getLogger(SampleUploadController.class.getName()).log(Level.SEVERE, null, ex);
    }



   return new ModelAndView("upload", "msg", "File ( " + f.getOriginalFilename() + ") successfully uploaded.");
}

}

D.C.
  • 15,340
  • 19
  • 71
  • 102

3 Answers3

27

To get reference to ServletContext, your class can implement ServletContextAware

ServletContext is also accessible in the web application container under the bean name servletContext, so you can inject it like any other bean in Spring. This works even if you don't have a session, and dependency injection is the Spring way.

Raedwald
  • 46,613
  • 43
  • 151
  • 237
axtavt
  • 239,438
  • 41
  • 511
  • 482
  • not working. in case i am not inside a servlet... i get the "context" object, but getContextPath returns null. – OhadR Apr 16 '14 at 16:23
11

I thought getting a ServletContext() then using realPath() may work, but I don't have a reference to ServletContext

Yes you do. See HttpServletRequest.getSession().getServletContext()

Kevin
  • 30,111
  • 9
  • 76
  • 83
  • 4
    This won't work, however, if you don't have a session and wish to remain sessionless. See the answer from axtavt. – Paul Jun 22 '11 at 15:05
0

Getting server url using ServletContext is not safe across different environments.

It would be better to retrieve the url from a property file.

luke
  • 3,531
  • 1
  • 26
  • 46