Spring 文件上传 学习笔记

owo

  • Spring Boot 工程嵌入的tomcat限制了请求的文件大小,每个文件的配置最大1Mb,单词请求的文件的总数不能大于10Mb
  • 可以在配置文件(如application.properties)里更改
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

示例

@RestController
public class FileUploadController {

//    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @PostMapping("/upload")
    public String up(String nickname, MultipartFile photo, HttpServletRequest request) throws IOException {
        System.out.println(nickname);
        System.out.println(photo.getOriginalFilename());
//        System.out.println(System.getProperty("user.dir"));
        System.out.println(photo.getContentType());
        String path = request.getServletContext().getRealPath("/upload/");
        System.out.println(path);
        saveFile(photo, path);
        return "上传成功";
    }

    public void saveFile(MultipartFile photo, String path) throws IOException {
        File dir = new File(path);
        if(!dir.exists()) {
            dir.mkdir();
        }
        File file = new File(path, photo.getOriginalFilename());
        photo.transferTo(file);
    }

}
img_show