亲宝软件园·资讯

展开

Spring Cloud Feign文件上传 Spring Cloud Feign的文件上传实现的代码实例

翟永超 人气:0
想了解Spring Cloud Feign的文件上传实现的代码实例的相关内容吗,翟永超在本文为您仔细讲解Spring Cloud Feign文件上传的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Spring,Cloud,Feign文件上传,Spring,Cloud,Feign,上传,下面大家一起来学习吧。

在Spring Cloud封装的Feign中并不直接支持传文件,但可以通过引入Feign的扩展包来实现,本来就来具体说说如何实现。

服务提供方(接收文件)

服务提供方的实现比较简单,就按Spring MVC的正常实现方式即可,比如:

@RestController
public class UploadController {

  @PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
  public String handleFileUpload(@RequestPart(value = "file") MultipartFile file) {
    return file.getName();
  }
  
}

服务消费方(发送文件)

在服务消费方由于会使用Feign客户端,所以在这里需要在引入feign对表单提交的依赖,具体如下:

<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>

定义FeignClient,假设服务提供方的服务名为 upload-server

@FeignClient(value = "upload-server", configuration = TestServiceClient.MultipartSupportConfig.class)
public interface UploadService { 
  @PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
  String handleFileUpload(@RequestPart(value = "file") MultipartFile file);
 
  @Configuration
  class MultipartSupportConfig {
    @Bean
    public Encoder feignFormEncoder() {
      return new SpringFormEncoder();
    }
  } 
}

在启动了服务提供方之后,尝试在服务消费方编写测试用例来通过上面定义的Feign客户端来传文件,比如:

@Test
@SneakyThrows
public 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));
}

加载全部内容

相关教程
猜你喜欢
用户评论