从Spring Controller获取Web App根目录

我正在尝试将上传的多部分文件写入文件系统。 我有一个名为audio的目录,它位于我的Web应用程序的根目录中(不在WEB-INF内部,但在它旁边,它可以像css和javascript一样公开访问)。

我想将上传的文件写入该目录,但我似乎无法获得我需要的路径。 我认为获得ServletContext()然后使用realPath()可能会工作,但我没有通过Spring控制器引用ServletContext。 谢谢任何肝脏

@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 /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."); } 

}

我认为获取ServletContext()然后使用realPath()可能会工作,但我没有对ServletContext的引用

是的你是。 请参阅HttpServletRequest.getSession()。getServletContext()

要获得对ServletContext引用,您的类可以实现ServletContextAware

编辑: ServletContext也可以在bean名称servletContext下的Web应用程序容器中servletContext ,因此您可以像在Spring中的任何其他bean一样注入它。

使用ServletContext获取服务器URL在不同环境中是不安全的。

最好从属性文件中检索url。