在Spring MVC应用程序的webcontent或web-inf中创建一个新文件


   @RequestMapping(value = "/upload", method = RequestMethod.POST)
   public @ResponseBody String upload(MultipartHttpServletRequest request, HttpServletResponse response) {                 
     Iterator<String> itr =  request.getFileNames();
     String fileName=itr.next();
     MultipartFile file = request.getFile(fileName);
     if (!file.isEmpty()) {
            try {
                File fileNew=new File(file.getOriginalFilename());

                byte[] bytes = file.getBytes();
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fileNew));
                stream.write(bytes);
                stream.close();
                System.out.println(fileNew.getAbsolutePath());
                return "You successfully uploaded " + fileName + " into " + fileName + "-uploaded !";
            } catch (Exception e) {
                return "You failed to upload " + fileName + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + fileName + " because the file was empty.";
        }

  }

文件被创建在

F:springsource-tool-suite-2.8.1.RELEASE-e3.7.1-win32springsourcests-2.8.1.RELEASE

长话短说,我想在webcontentWEB-INF创建一个新文件。

谢谢! !

  • 可以在控制器中自动连接ServletContext,然后从您的方法获得真实路径

    @AutowiredServletContext servletContext;

  • 或者作为vzamanillo的回答

    request.getSession().getServletContext().getRealPath("/WEB-INF/");

Try with

File fileNew = new File(request.getSession().
getServletContext().getRealPath("/WEB-INF/"), file.getOriginalFilename());

关于ServletContext.getRealPath()的文档

相关内容

  • 没有找到相关文章

最新更新