从Spring Controller获取Web App根目录 [英] Get Web App root from Spring Controller

查看:644
本文介绍了从Spring Controller获取Web App根目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图把一个上传的多部分文件写入文件系统。我有一个名为音频的目录,位于我的Web应用程序的根目录(不在WEB-INF内部,但在其旁边,可公开访问,如css和javascript)。

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

  @RequestMapping(value =/ uploadSample)
public ModelAndView上传(HttpServletRequest请求,HttpServletResponse响应,@RequestParam(文件)MultipartFile f){

if(f == null){
返回新的ModelAndView(upload,msg,文件为空。);

try {
//我需要将AUDIO_PATH设置为< 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);
}



成功上传新的ModelAndView(upload,msg,File(+ f.getOriginalFilename()+)。 );

$ / code>

}

解决方案


我以为得到一个ServletContext()
然后使用realPath()可能工作,但我
没有引用
ServletContext

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


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

}

解决方案

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()

这篇关于从Spring Controller获取Web App根目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆