File transfer is not directly supported in Feign encapsulated by Spring Cloud, but it can be implemented by introducing Feign extension packages, so we will talk about how to implement it in detail.
Service provider (receive files)
The implementation of the service provider is relatively simple, just follow the normal implementation method of Spring MVC, such as:
@RestControllerpublic class UploadController { @PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public String handleFileUpload(@RequestPart(value = "file") MultipartFile file) { return file.getName(); } }Service consumer (send file)
Since the service consumer will use the Feign client, it is necessary to introduce feign's dependency on form submission here, as follows:
<dependency> <groupId>io.github.openfeign.form</groupId> <artifactId>feign-form</artifactId> <version>3.0.3</version></dependency><dependency> <groupId>io.github.openfeign.form</groupId> <artifactId>feign-form-spring</artifactId> <version>3.0.3</version></dependency><dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId></dependency>
Define FeignClient, assuming that the service provider's service name is upload-server
@FeignClient(value = "upload-server", configuration = TestServiceClient.MultipartSupportConfig.class)public interface UploadService { @PostMapping(value = "/uploadFile", consumers = MediaType.MULTIPART_FORM_DATA_VALUE) String handleFileUpload(@RequestPart(value = "file") MultipartFile file); @Configuration class MultipartSupportConfig { @Bean public Encoder feignFormEncoder() { return new SpringFormEncoder(); } } }After starting the service provider, try to write test cases on the service consumer to pass the file through the Feign client defined above, such as:
@Test@SneakyThrowspublic void testHandleFileUpload() { File file = new File("files/aaa.txt"); DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file", MediaType.TEXT_PLAIN_VALUE, true, file.getName()); try (InputStream input = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()) { IOUtils.copy(input, os); } catch (Exception e) { throw new IllegalArgumentException("Invalid file: " + e, e); } MultipartFile multi = new CommonsMultipartFile(fileItem); log.info(testServiceClient.handleFileUpload(multi));}The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.