Feign 接口上传文件

1)Encoder 配置注入容器

2)

public class SpringFormEncoderExtension extends FormEncoder {

    /**
     * 使用默认的feign编码器
     *
     * @author*/
    public SpringFormEncoderExtension() {
        this(new Default());
    }

    /**
     * 使用传入的编码器并提供对多文件的支持
     *
     * @param encoder 编码器
     * @author*/
    public SpringFormEncoderExtension(Encoder encoder) {
        super(encoder);

        MultipartFormContentProcessor processor = (MultipartFormContentProcessor) getContentProcessor(ContentType.MULTIPART);
        processor.addWriter(new SpringSingleMultipartFileWriter());
        processor.addWriter(new SpringManyMultipartFilesWriter());
    }

    /**
     * 模仿FormEncode对其进行扩展支持多文件传递
     *
     * @param object   传递内容
     * @param bodyType 传递类型
     * @param template 传递路径
     * @author*/
    @Override
    public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException {
        if (bodyType.equals(MultipartFile.class)) {
            MultipartFile file = (MultipartFile) object;
            Map data = Collections.singletonMap(file.getName(), object);
            super.encode(data, MAP_STRING_WILDCARD, template);
        } else if (bodyType.equals(MultipartFile[].class)) {
            MultipartFile[] file = (MultipartFile[]) object;
            if (file != null) {
                Map data = Collections.singletonMap(file.length == 0 ? "" : file[0].getName(), object);
                super.encode(data, MAP_STRING_WILDCARD, template);
            }
        } else {
            super.encode(object, bodyType, template);
        }
    }
}

 

3)

@FeignClient(name = "storage-service", fallback = UploadFeignClientFallback.class, configuration = FeignConfig.class)
public interface UploadFeignClient {

    @PostMapping(value = "/storage/upload/goods/{serverName}/{shopId}",produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}
            , consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    Map uploadGoods(@RequestPart("file") MultipartFile file, @PathVariable("serverName") String serverName
    , @PathVariable("shopId") String shopId);
}

 简化解决方案,以上的方案有一些问题,具体什么问题 请自测。现在的方案是这样解决的:

@Configuration
public class FeignConfig {

    @Bean
    public Encoder multipartFormEncoder() {
        return new SpringFormEncoder(new SpringEncoder(new ObjectFactory<HttpMessageConverters>() {
            @Override
            public HttpMessageConverters getObject() throws BeansException {
                return new HttpMessageConverters(new RestTemplate().getMessageConverters());
            }
        }));
    }
}

 


posted @ 2019-06-26 17:55  caozengling  阅读(2403)  评论(0编辑  收藏  举报