1. 概述
本快速教程重點介紹如何使用 Spring 的 RestTemplate 上傳多部分文件。
我們將看到單個文件和多個文件 – 使用 RestTemplate 上傳。
2. 什麼是 HTTP 多部分請求?
簡單來説,基本的 HTTP POST 請求主體包含以鍵值對的形式表示的表單數據。
另一方面,HTTP 客户端可以構造 HTTP 多部分請求,將文本或二進制文件發送到服務器;主要用於文件上傳。
另一個常見用例是發送帶有附件的電子郵件。多部分文件請求將大型文件分解為較小的塊,並使用邊界標記來指示塊的開始和結束。
瞭解更多關於多部分請求的信息 這裏。
3. Maven 依賴
此單個依賴項就足以滿足客户端應用程序的需求:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>4. 單文件上傳服務器
文件服務器 API 暴露了兩個 REST 端點,用於分別上傳單個文件和多個文件:
- POST /fileserver/singlefileupload/
- POST /fileserver/multiplefileupload/
5. 上傳單個文件
首先,讓我們看看使用 RestTemplate 進行單個文件上傳。
我們需要創建一個包含 header 和 body 的 HttpEntity。 將 content-type header 的值設置為 MediaType.MULTIPART_FORM_DATA。 當設置此 header 時,RestTemplate 會自動將文件數據以及一些元數據進行序列化。
元數據包括文件名、文件大小和文件內容類型(例如 text/plain):
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);接下來,將請求體構建為 LinkedMultiValueMap 類的實例。 LinkedMultiValueMap 包裝了 LinkedHashMap,用於存儲每個鍵對應的值列表,並使用 LinkedList 存儲。
在我們的示例中,getTestFile( ) 方法會動態生成一個文件並返回一個 FileSystemResource:
MultiValueMap<String, Object> body
= new LinkedMultiValueMap<>();
body.add("file", getTestFile());最後,構造一個封裝了頭部和主體對象的 HttpEntity 實例,並使用 RestTemplate 將其發佈。
注意,單文件上傳指向 /fileserver/singlefileupload/ 端點。
最終,調用 restTemplate.postForEntity( ) 完成了連接到給定 URL 並將文件發送到服務器的任務:
HttpEntity<MultiValueMap<String, Object>> requestEntity
= new HttpEntity<>(body, headers);
String serverUrl = "http://localhost:8082/spring-rest/fileserver/singlefileupload/";
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate
.postForEntity(serverUrl, requestEntity, String.class);6. 上傳多個文件
在多個文件上傳中,與單文件上傳唯一的區別在於構建請求體的方式。
讓我們創建多個文件並將它們使用相同的鍵添加到 MultiValueMap 中。
顯然,請求 URL 應指向多個文件上傳的端點:
MultiValueMap<String, Object> body
= new LinkedMultiValueMap<>();
body.add("files", getTestFile());
body.add("files", getTestFile());
body.add("files", getTestFile());
HttpEntity<MultiValueMap<String, Object>> requestEntity
= new HttpEntity<>(body, headers);
String serverUrl = "http://localhost:8082/spring-rest/fileserver/multiplefileupload/";
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate
.postForEntity(serverUrl, requestEntity, String.class);始終可以使用多文件上傳功能進行單文件上傳。
7. 結論
綜上所述,我們觀察到使用 Spring 的 RestTemplate 傳輸 MultipartFile 的一個案例。