从弹簧控制器获取Web应用程序根目录
我正在尝试将上传的多部分文件写入文件系统。我有一个名为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 <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.");
}
}