1. 程式人生 > 實用技巧 >SpringBoot - 04上傳檔案

SpringBoot - 04上傳檔案

SpringBoot - 04上傳檔案

(1)靜態檔案:上傳頁面 static/fileUpload.html

<html>
<head>
    <title>upload</title>
</head>
<body>
    <form action="/fileUploadController" method="post" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type
="submit" value="Submit"/> </form> </body> </html>

(2)Controller

@RestController
public class FileUploadController {

    /**
     * 檔案上傳
     * @param file  必須要和前端頁面傳遞的引數值一致
     * @return
     */
    @PostMapping("/fileUploadController")
    public String fileUpload(MultipartFile file) throws
Exception{ System.out.println(file.getOriginalFilename()); file.transferTo(new File("e:/"+file.getOriginalFilename())); return "OK"; } }

(3)啟動類

@SpringBootApplication
public class SpringBoot04UploadApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBoot04UploadApplication.
class, args); } }

(4)測試:訪問http://localhost:8080/fileUpload.html

上傳之後,返回"OK"

(5)上傳檔案過大

org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 1048576 bytes.

application.properties新增配置

spring.servlet.multipart.max-file-size=10MB     // 配置單個上傳檔案的大小限制
spring.servlet.multipart.max-request-size=20MB  // 配置在一次請求中上傳檔案的總容量限制