从Spring Controller获取Web App根目录

编程入门 行业动态 更新时间:2024-10-28 05:17:14
本文介绍了从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根目录

本文发布于:2023-08-02 11:52:55,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:根目录   Controller   Spring   App   Web

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!