知識庫 / Spring / Spring Boot RSS 訂閱

Spring 中多部分請求處理

Spring Boot
HongKong
10
12:31 PM · Dec 06 ,2025

1. 引言

本教程將重點介紹 Spring Boot 中發送多部分請求的各種機制。多部分請求是指通過單個 HTTP 方法調用,將多種不同類型的數據(通過邊界分隔)一起發送。

通常,我們可以發送複雜的 JSON、XML、CSV 數據,以及在請求中傳輸多部分文件(例如音頻或圖像文件)。 此外,我們還可以將簡單的鍵值對數據與多部分文件一起發送。

現在,讓我們來看看我們如何發送這些數據。

2. 使用 @ModelAttribute</em/>

讓我們考慮一個使用表單發送員工數據(包括姓名和文件)的簡單用例。

首先,我們將創建一個 Employee 抽象類來存儲表單數據:

public class Employee {
    private String name;
    private MultipartFile document;
}

然後我們使用 Thymeleaf 生成表單:

<form action="#" th:action="@{/employee}" th:object="${employee}" method="post" enctype="multipart/form-data">
    <p>name: <input type="text" th:field="*{name}" /></p>
    <p>document:<input type="file" th:field="*{document}" multiple="multiple"/>
    <input type="submit" value="upload" />
    <input type="reset" value="Reset" /></p>
</form>

需要注意的是,我們在視圖中聲明 enctypemultipart/form-data

最後,我們將創建一個方法來接受表單數據,包括多部分文件:

@PostMapping(path = "/employee", consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
public String saveEmployee(@ModelAttribute Employee employee) {
    employeeService.save(employee);
    return "employee/success";
}

以下是翻譯後的內容:

在此,兩個特別重要的細節是:

  • consumes 屬性值設置為 multipart/form-data
  • @ModelAttribute 已捕獲所有表單數據,包括上傳的文件,到 Employee POJO 中

3. 使用 <em @RequestPart 標註

此註解 將多部分請求的一部分與方法參數關聯起來,這對於將複雜多屬性數據作為負載(例如 JSON 或 XML)發送非常有用。

讓我們創建一個具有兩個參數的方法,第一個類型為 Employee,第二個類型為 MultipartFile。 此外,我們還將這兩個參數標記為

@PostMapping(path = "/requestpart/employee", consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
public ResponseEntity<Object> saveEmployee(@RequestPart Employee employee, @RequestPart MultipartFile document) {
    employee.setDocument(document);
    employeeService.save(employee);
    return ResponseEntity.ok().build();
}

現在,要查看此標註的效果,我們將使用 MockMultipartFile 創建測試:

@Test
public void givenEmployeeJsonAndMultipartFile_whenPostWithRequestPart_thenReturnsOK() throws Exception {
    MockMultipartFile employeeJson = new MockMultipartFile("employee", null,
      "application/json", "{\"name\": \"Emp Name\"}".getBytes());

    mockMvc.perform(multipart("/requestpart/employee")
      .file(A_FILE)
      .file(employeeJson))
      .andExpect(status().isOk());
}

需要注意的是,我們已將 Employee 部分的內容類型設置為 application/JSON。我們還以 JSON 文件形式發送這些數據,除了多部分文件之外。

有關如何測試多部分請求的更多詳細信息,請參見此處。

4. 使用 @RequestParam</em/>

另一種發送多部分數據的方法是使用 @RequestParam</em/>。這尤其適用於簡單的鍵值對數據,這些數據與文件一起發送:

@RequestMapping(path = "/requestparam/employee", method = POST, consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
public ResponseEntity<Object> saveEmployee(@RequestParam String name, @RequestPart MultipartFile document) {
    Employee employee = new Employee(name, document);
    employeeService.save(employee);
    return ResponseEntity.ok().build();
}

讓我們編寫此方法測試用例以演示:

@Test
public void givenRequestPartAndRequestParam_whenPost_thenReturns200OK() throws Exception {
    mockMvc.perform(multipart("/requestparam/employee")
      .file(A_FILE)
      .param("name", "testname"))
      .andExpect(status().isOk());
}

5. 結論

在本文中,我們學習瞭如何在 Spring Boot 中有效地處理多部分請求。

最初,我們使用模型屬性發送多部分表單數據。然後,我們研究瞭如何使用 @RequestPart@RequestParam 註解分別接收多部分數據。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.