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()); } })); } }