javaweb文件上传

来源:互联网 发布:外贸薪资 知乎 编辑:程序博客网 时间:2024/06/03 08:48

首先要有这两个JAR包

jsp页面如下:

<body>      <form method="post" enctype="multipart/form-data" action="user/aaa">        <input type="file" name="file">        <input type="submit" value="提交">    </form>  </body>
action如下:

  @RequestMapping(value = "/aaa",method = RequestMethod.POST)      public String login(@Validated User user, BindingResult br, Model model,@RequestParam("file") MultipartFile file){        if (br.hasErrors()){            return "MyJsp";        }        //分别获取的是变量名file---文件类型---文件名        System.out.println(file.getName()+"---"+file.getContentType()+"---"+file.getOriginalFilename());        try {            if (!file.isEmpty()){            //使用StreamsAPI方式拷贝文件                Streams.copy(file.getInputStream(),new FileOutputStream("D:/myWork/StudentTranstation/WebRoot/images/"+file.getOriginalFilename()),true);            }            System.out.println("上传成功,路径为:D:/myWork/StudentTranstation/WebRoot/images/"+file.getOriginalFilename());        } catch (IOException e) {            System.out.println("文件上传失败");            e.printStackTrace();        }        return "MyJsp";    }
则文件保存在
  D:/myWork/StudentTranstation/WebRoot/images/
这个路径下


控制台打印输出

上传成功,路径为:D:/myWork/StudentTranstation/WebRoot/images/+文件名字

jar包+代码下载