4、SpringBoot之文件上传

步骤

  1. POM文件
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
    </exclusions>
</dependency>
  1. 编写上传页面
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/fileUploadController" method="post" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit" value="okok">
    </form>
</body>
</html>
  1. 编写Controller
@RestController
public class FileUploadController {
//    文件上传
    @PostMapping("/fileUploadController")
    public String fileUpload(MultipartFile file)throws Exception{
        System.out.println(file.getOriginalFilename());
        file.transferTo(new File("D:/" + file.getOriginalFilename()));
        return "OK";
    }
}
  1. 修改上传文件大小

上传文件如果超过设定的大小就会报错

Maximum upload size exceeded; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 1048576 bytes.

上传文件的大小默认是1m

可以通过配置文件配置文件上传的大小限制

#配置单个上传文件的大小的限制
spring.servlet.multipart.max-file-size=2MB
#配置在一次请求当中上传文件的总容量的大小,默认是10MB
spring.servlet.multipart.max-request-size=10MB
posted @ 2020-08-28 12:42  lawrence林  阅读(172)  评论(0编辑  收藏  举报