Uploading MultipartFile with Spring RestTemplate – 用Spring RestTemplate上传MultipartFile

最后修改: 2018年 7月 20日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

This quick tutorial focuses on how to upload a multipart file using Spring’s RestTemplate.

这个快速教程主要介绍如何使用Spring的RestTemplate上传一个多部分文件。

We’ll see both a single file and multiple files – upload using the RestTemplate.

我们将看到单个文件和多个文件–上传 使用RestTemplate.

2. What Is an HTTP Multipart Request?

2.什么是HTTP多部分请求?

Simply put, a basic HTTP POST request body holds form data in name/value pairs.

简单地说,一个基本的HTTP POST请求体以名/值对的形式保存表单数据。

On the other hand, HTTP clients can construct HTTP multipart requests to send text or binary files to the server; it’s mainly used for uploading files.

另一方面,HTTP客户端可以构建HTTP多部分请求,向服务器发送文本或二进制文件;它主要用于上传文件。

Another common use-case is sending the email with an attachment. Multipart file requests break a large file into smaller chunks and use boundary markers to indicate the start and end of the block.

另一个常见的用例是发送带有附件的电子邮件。多部分文件请求将一个大文件分成小块,并使用边界标记来指示块的开始和结束。

Explore more about multipart requests here.

探索更多关于多部分请求的信息这里

3. Maven Dependency

3.Maven的依赖性

This single dependency is enough for the client application:

这个单一的依赖性对客户应用来说已经足够了。

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>5.2.2.RELEASE</version>
</dependency>

4. The File Upload Server

4.文件上传服务器

The file server API exposes two REST endpoints for uploading single and multiple files respectively:

文件服务器API暴露了两个REST端点,分别用于上传单个和多个文件。

  • POST /fileserver/singlefileupload/
  • POST /fileserver/multiplefileupload/

5. Uploading a Single File

5.上传单个文件

First, let’s see single file upload using the RestTemplate.

首先,让我们看看使用RestTemplate的单文件上传。

We need to create HttpEntitywith header and body. Set the content-type header value to MediaType.MULTIPART_FORM_DATA. When this header is set, RestTemplate automatically marshals the file data along with some metadata.

我们需要创建HttpEntity与头和主体。将content-type头的值设置为MediaType.MULTIPART_FORM_DATA。当这个头被设置时,RestTemplate会自动将文件数据与一些元数据一起打包。

Metadata includes file name, file size, and file content type (for example text/plain):

元数据包括文件名称、文件大小和文件内容类型(例如text/plain)。

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);

Next, build the request body as an instance of LinkedMultiValueMap class. LinkedMultiValueMap wraps LinkedHashMap storing multiple values for each key in a LinkedList.

接下来,将请求主体构建为LinkedMultiValueMap类的一个实例。LinkedMultiValueMap包装了LinkedHashMap,为LinkedList中的每个键存储多个值。

In our example, the getTestFile( ) method generates a dummy file on the fly and returns a FileSystemResource:

在我们的例子中,getTestFile()方法即时生成了一个假文件,并返回一个FileSystemResource

MultiValueMap<String, Object> body
  = new LinkedMultiValueMap<>();
body.add("file", getTestFile());

Finally, construct an HttpEntity instance that wraps the header and the body object and post it using a RestTemplate.

最后,构造一个HttpEntity实例,它包装了头和主体对象,并使用RestTemplate发布它。

Note that the single file upload points to the /fileserver/singlefileupload/ endpoint.

注意,单一文件上传指向/fileserver/singlefileupload/端点。

In the end, the call restTemplate.postForEntity( ) completes the job of connecting to the given URL and sending the file to the server:

最后,调用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. Uploading Multiple Files

6.上传多个文件

In multiple file upload, the only change from single file upload is in constructing the body of the request.

在多文件上传中,与单文件上传相比,唯一的变化是构建请求的主体。

Let’s create multiple files and add them with the same key in MultiValueMap.

让我们创建多个文件,并在MultiValueMap添加相同的键

Obviously, the request URL should refer to endpoint for multiple file upload:

很明显,请求的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);

It’s always possible to model single file upload using the multiple file upload.

它总是可以使用多文件上传的模式来上传单个文件。

7. Conclusion

7.结论

In conclusion, we saw a case of MultipartFile transfer using Spring RestTemplate.

最后,我们看到了一个使用Spring RestTemplate进行MultipartFile传输的案例。

As always, the example client and server source code is available over on GitHub.

一如既往,客户端和服务器的示例源代码可在GitHub上获得over