4、SpringBoot之檔案上傳
阿新 • • 發佈:2020-08-28
步驟
- 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>
- 編寫上傳頁面
<!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>
- 編寫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"; } }
- 修改上傳檔案大小
上傳檔案如果超過設定的大小就會報錯
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