我有两个微服务:
过程:
@PostMapping(value ="/create")
ResponseEntity<Response> createVideo(@RequestParam("file") MultipartFile multipartFile)
{
videoRestClientService.upload(multipartFile);
return new ResponseEntity<Response>(new Response("video has been stored"), HttpStatus.OK);
}
public Response upload(MultipartFile multipartFile){
RestClient restClient = RestClient.create("http://localhost:8095");
Response response = restClient.post()
.uri("/uploadfile")
.contentType(...)
.body(multipartFile)
.retrieve()
.body(Response.class);
}
-> 在 videoStore 微服务中
@PostMapping("/uploadfile")
public ResponseEntity<Response> uploadFile(@RequestParam("file") MultipartFile multipartFile) {
Response response = fileSystemStorage.storeFile(multipartFile);
return new ResponseEntity<Response>(response, HttpStatus.OK);
}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>6.1.2</version>
</dependency>
问题:
备注:
是否可以使用restClient来发布multipartFile?
不知道你现在解决了吗?但答案是肯定的。我也在做同样的事情,经过一天的研究后才让它发挥作用。这就是您所需要的:
import org.springframework.web.client.RestClient;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
public Response upload (MultipartFile multipartFile) {
// I am not create RestClient like this. I use @Autowired instead
RestClient restClient = RestClient.create("http://localhost:8095");
MultiValueMap<String, Resource> body = new LinkedMultiValueMap<>();
body.add("file", multipartFile.getResource());
Response response = restClient.post()
.uri("/uploadfile")
// You can try using .contentType instead of set header. In my case it not works, my app said
// it need the boundary so I have to set header "Content-Type".
.header("Content-Type", MediaType.MULTIPART_FORM_DATA_VALUE + "; boundary=yourChoiceOfBoundary")
// .contentType(MediaType.MULTIPART_FORM_DATA) // Not need because already set on header
.body(body)
.retrieve()
.body(Response.class);
return response;
}