文件上传在spring-boot中是极为简单的,下面写个简单的demo
第一步:pom.xml加入如下jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
只需引入devtools一个包即可
第二步:编写controller层代码
@PostMapping("/upload")
public String upload(@RequestParam("file")MultipartFile file,
RedirectAttributes redirectAttributes) throws IOException {
if (file.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "请选择一个文件!");
return "redirect:uploadStatus";
}
byte[] bytes = file.getBytes();
Path path = Paths.get("E:\\practiceSpace\\springbootfileupload",file.getOriginalFilename());
Files.write(path,bytes);
redirectAttributes.addFlashAttribute("message","上传成功");
return "redirect:uploadStatus";
}
@PostMapping 也可换成 @RequestMapping
代码中 return "redirect:uploadStatus";是返回到一个上传结果展示页面,
真正用于文件上传的代码只有如下三行:
byte[] bytes = file.getBytes();
Path path =Paths.get("E:\\practiceSpace\\springbootfileupload",file.getOriginalFilename());
Files.write(path,bytes);