springboot系列16:文件上传


文件上传用到的场景也比较多,如头像的修改、相册应用、附件的管理等等,今天就来学习下在springboot框架下应用文件上传技术。

1、pom 配置

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
    

2、application.properties配置上传文件的大小

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

3、上传页面




Spring Boot file upload example



4、上传结果页面




SpringBoot - 文件上传结果

5、上传文件controller

@Controller
public class UploadController {

    private static String UPLOADED_FOLDER = "E://temp//";

    @GetMapping("/")
    public String index() {
        return "index";
    }

    @PostMapping("/upload")
    public String singleFileUpload(@RequestParam("file") MultipartFile file,
                                   RedirectAttributes redirectAttributes) {
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "请选择一个文件上传");
            return "redirect:uploadStatus";
        }

        try {
            byte[] bytes = file.getBytes();
            File pathFile = new File(UPLOADED_FOLDER);
            if (!pathFile.exists()){
                pathFile.mkdirs();
            }
            Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
            Files.write(path, bytes);

            redirectAttributes.addFlashAttribute("message",
                    "文件上传成功:'" + file.getOriginalFilename() + "'");

        } catch (IOException e) {
            e.printStackTrace();
        }

        return "redirect:/result";
    }

    @GetMapping("/result")
    public String result() {
        return "result";
    }
}