我想将上传的文件写入该目录,但似乎无法获得所需的路径。我以为得到一个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根目录
发布评论