1. 程式人生 > 實用技巧 >Spring Boot 檔案上傳

Spring Boot 檔案上傳

Spring Boot 檔案上傳

建立專案

Spring Initializr 建立 Spring Boot 專案,模板引擎選擇 Thymeleaf。

專案的 pom.xml 如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.yin</groupId>
    <artifactId>file-upload</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>file-upload</name>
    <description>Spring Boot 檔案上傳練習</description>

    <properties>
        <java.version>11</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </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>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-configuration-processor
                            </artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

編寫頁面

在專案 resources/templates 資料夾下建立頁面 FileUpload.html

注意:表單 method="post"enctype="multipart/form-data"。多檔案上傳的 input 標籤需要標註 multiple

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>檔案上傳</title>
</head>
<body>
<h1>檔案上傳</h1>
<form method="post" action="/fileUpload" enctype="multipart/form-data">
    使用者名稱:
    <label>
        <input type="text" name="username">
    </label>
    <br>
    單檔案上傳:<input type="file" name="singleFile">
    <br>
    多檔案上傳:<input type="file" name="multipleFiles" multiple>
    <br>
    <input type="submit" value="提交">
</form>
</body>
</html>

編寫 Controller

建立 Controller 處理請求,Spring Boot 進行檔案上傳已經十分方便。以單檔案上傳為例,多檔案上傳基本一樣,陣列處理即可。

  • @RequestPart("singleFile") MultipartFile singleFile :註解 @RequestPart("singleFile") 取出表單中 name="singleFile"input 項,將檔案封裝到 MultipartFile singleFile,在方法中直接對其進行操作即可。
  • getOriginalFilename() 方法獲取上傳的檔名
  • getSize() 方法獲取檔案大小(單位byte)
  • transferTo() 方法可直接將檔案進行儲存;想自己手動進行這一操作,也可以呼叫其 getBytes() 或者 getInputStream() 方法。

多檔案上傳只需陣列處理 @RequestPart("multipleFiles") MultipartFile[] multipleFiles ,在方法中利用迴圈逐個進行處理即可。

package com.yin.fileupload.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * FileUploadController
 *
 * @author Yin Guiqing
 */
@Controller
public class FileUploadController {
    /**
     * 自定義檔案儲存路徑,在 application.properties 中設定
     */
    @Value("${file.upload.path}")
    private String path;

    /**
     * 去檔案上傳頁面
     */
    @GetMapping("/")
    public String uploadPage() {
        return "FileUpload";
    }

    /**
     * 處理檔案上傳請求
     */
    @ResponseBody
    @PostMapping("/fileUpload")
    public String fileUpload(@RequestParam("username") String username,
                             @RequestPart("singleFile") MultipartFile singleFile,
                             @RequestPart("multipleFiles") MultipartFile[] multipleFiles) throws IOException {
        System.out.println(username + " 上傳檔案");
        // 處理單檔案上傳
        // 檔名
        String singleFileName = singleFile.getOriginalFilename();
        // 檔案大小(位元組)
        long singleFileSize = singleFile.getSize();
        // 儲存檔案
        if (!singleFile.isEmpty()) {
            singleFile.transferTo(new File(path + singleFileName));
        }
        String msg1 = "單檔案上傳成功!檔名:" + singleFileName
                + ",檔案大小(byte):" + singleFileSize;
        System.out.println(msg1);

        // 處理多檔案上傳
        // 檔案個數
        int length = multipleFiles.length;
        System.out.println("多檔案上傳個數:" + length);
        for (MultipartFile multipleFile : multipleFiles) {
            // 檔名
            String multipleFileName = multipleFile.getOriginalFilename();
            // 檔案大小(位元組)
            long multipleFileSize = multipleFile.getSize();
            // 儲存檔案
            if (!multipleFile.isEmpty()) {
                multipleFile.transferTo(new File(path + multipleFileName));
            }
            String msg2 = "檔案上傳成功!檔名:" + multipleFileName
                    + ",檔案大小(byte):" + multipleFileSize;
            System.out.println(msg2);
        }
        return "上傳完畢";
    }
}

相關屬性設定

application.properties 中的相關屬性設定

Spring Boot 預設單個檔案最大 1MB,單次請求最大 10MB,可根據需求進行設定。

#單個檔案最大
spring.servlet.multipart.max-file-size=100MB
#單次請求最大
spring.servlet.multipart.max-request-size=1024MB

#自定義檔案儲存路徑
file.upload.path=D:/

效果演示

專案結構:

頁面:

結果:

可在指定的位置檢視已上傳的檔案


程式碼已上傳至:https://gitee.com/ME_WE/spring-boot-practice