从Spring Controller获取Web App根目录

D.C*_*.C. 12 java file-io spring

我正在尝试将上传的多部分文件写入文件系统.我有一个名为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.");
}
Run Code Online (Sandbox Code Playgroud)

}

axt*_*avt 27

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

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


Kev*_*vin 11

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

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

  • 但是,如果您没有会话并希望保持无会话状态,则无法使用此功能.请参阅axtavt的答案. (4认同)