1.重写SpringFormEncoder的encode方法
public class FeignSpringFormEncoder extends SpringFormEncoder {
public FeignSpringFormEncoder(Encoder delegate) {
super(delegate);
MultipartFormContentProcessor processor = (MultipartFormContentProcessor) getContentProcessor(MULTIPART);
processor.addWriter(new SpringSingleMultipartFileWriter());
processor.addWriter(new SpringManyMultipartFilesWriter());
}
@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);
return;
} else if (bodyType.equals(MultipartFile[].class)) {
MultipartFile[] file = (MultipartFile[]) object;
if (file != null) {
Map data = Collections.singletonMap(file.length == 0 ? "" : "files", object);
super.encode(data, MAP_STRING_WILDCARD, template);
return;
}
}
super.encode(object, bodyType, template);
}
}
2.写Feign配置类
@Configuration
public class FeignMultipartSupportConfig {
@Autowired
private ObjectFactory<HttpMessageConverters> messageConverters;
/**
* 兼容文件传递
* @return
*/
@Bean
public Encoder feignFormEncoder() {
return new FeignSpringFormEncoder(new SpringEncoder(messageConverters));
}
/**
* 开启feign日志
* @return
*/
@Bean
public Logger.Level logger() {
return Logger.Level.FULL;
}
}
3.在需要传递文件的FeignClient中增加配置
@FeignClient(name = "xxx", configuration = {FeignMultipartSupportConfig.class})
feign接口示例
@PostMapping(value = "xxx", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
Response uploadParkingRecord(@RequestPart("files") MultipartFile[] files);