文件上傳在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);