14. Spring Boot 文件上传接口

文件上传使用的是Post类型的接口。通过REST接口上传文件,需要使用到 MultipartFile 这个Spring MVC提供的类。

一个最简单的实例如下:

/** 文件上传*/
    @PostMapping("")
    public void upload(MultipartFile file) throws Exception {
        System.out.println(file.getName());
        System.out.println(file.getOriginalFilename());
        System.out.println(file.getSize());
        String folder = "D:\\Code\\uploadfiles";

        File localFile = new File(folder, new Date().getTime()+".txt");

        file.transferTo(localFile);
    }

接口测试

使用Postman进行测试,需要使用form-data类型的Body。然后设置key为file,并在value中选择文件。点击发送即可测试。

postman测试上传文件的接口

你可能感兴趣的:(14. Spring Boot 文件上传接口)