Feign-Form Encoder-实现基于Spring MultipartFile 和Spring FeignClient 表单文件上传

Feign-Form Encoder-实现基于Spring MultipartFile 和Spring FeignClient 表单文件上传

OpenFeign Form Encoder 支持对application/x-www-form-urlencoded and multipart/form-data 格式的表单数据编码。支持基于Spring MultipartFile 和Spring Cloud Netflix @FeignClient框架的表单文件上传。

1、在 pom.xml文件引入如下依赖:


  
    io.github.openfeign.form
    feign-form
    3.8.0
  
  
    io.github.openfeign.form
    feign-form-spring
    3.8.0
  


2、如何使用FeignForm Encoder

@FeignClient(
    name = "file-upload-service",
    configuration = FileUploadServiceClient.MultipartSupportConfig.class
)
public interface FileUploadServiceClient extends IFileUploadServiceClient {

  public class MultipartSupportConfig {

    @Autowired
    private ObjectFactory<HttpMessageConverters> messageConverters;

    @Bean
    public Encoder feignFormEncoder () {
      return new SpringFormEncoder(new SpringEncoder(messageConverters));
    }
  }
}

或者你不需要使用Spring的标准 encoder:

@FeignClient(
    name = "file-upload-service",
    configuration = FileUploadServiceClient.MultipartSupportConfig.class
)
public interface FileUploadServiceClient extends IFileUploadServiceClient {

  public class MultipartSupportConfig {

    @Bean
    public Encoder feignFormEncoder () {
      return new SpringFormEncoder();
    }
  }
}

这样就可以利用Spring FeignClient 框架实现Spring MultipartFile 格式文件表单提交。

3、其他特性

tf-haotrii-pham提供了一个特性—利用Apache commons-fileupload库处理multipart响应的解析,body 数据部分作为字节数组保存在内存中。要使用这个特性,需要在解码器的消息转换器列表中包含SpringManyMultipartFilesReader,并让Feign客户端返回一个MultipartFile数组:

@FeignClient(
    name = "${feign.name}",
    url = "${feign.url}"
    configuration = DownloadClient.ClientConfiguration.class
)
public interface DownloadClient {

  @RequestMapping("/multipart/download/{fileId}")
  MultipartFile[] download(@PathVariable("fileId") String fileId);

  class ClientConfiguration {

    @Autowired
    private ObjectFactory<HttpMessageConverters> messageConverters;

    @Bean
    public Decoder feignDecoder () {
      List<HttpMessageConverter<?>> springConverters =
            messageConverters.getObject().getConverters();

      List<HttpMessageConverter<?>> decoderConverters =
            new ArrayList<HttpMessageConverter<?>>(springConverters.size() + 1);

      decoderConverters.addAll(springConverters);
      decoderConverters.add(new SpringManyMultipartFilesReader(4096));

      HttpMessageConverters httpMessageConverters = new HttpMessageConverters(decoderConverters);

      return new SpringDecoder(new ObjectFactory<HttpMessageConverters>() {

        @Override
        public HttpMessageConverters getObject() {
          return httpMessageConverters;
        }
      });
    }
  }
}

参考

https://github.com/OpenFeign/feign-form

你可能感兴趣的:(Spring技术)