前言
原生的spring-feign接口只支持单个文件在服务间的传输,当传送多个文件时,则会报错:feign.codec.EncodeException: Could not write request: no suitable HttpMessageConverter found for request type [[Lorg.springframework.web.multipart.MultipartFile;] and content type [multipart/form-data]
提示:以下是本篇文章正文内容,下面案例可供参考
一、config配置文件
@Configurable
public class MultipartSupportConfig {
@Autowired
private ObjectFactory<HttpMessageConverters> messageConverters;
@Bean
public Encoder feignFormEncoder() {
return new SpringMultipartEncoder(new SpringEncoder(messageConverters));
}
}
二、SpringMultipartEncoder 多文件编码解析
重写encode方法,处理多文件
public class SpringMultipartEncoder extends SpringFormEncoder {
public SpringMultipartEncoder() {
this(new Default());
}
public SpringMultipartEncoder(Encoder delegate) {
super(delegate);
MultipartFormContentProcessor processor = (MultipartFormContentProcessor) getContentProcessor(ContentType.MULTIPART);
processor.addWriter(new SpringSingleMultipartFileWriter());
processor.addWriter(new SpringManyMultipartFilesWriter());
}
@Override
public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException {
if (bodyType != null && bodyType.equals(MultipartFile.class)) {
MultipartFile file = (MultipartFile) object;
if (file != null) {
Map<String, Object> data = Collections.singletonMap(file.getName(), object);
super.encode(data, MAP_STRING_WILDCARD, template);
return;
}
} else if (bodyType != null && bodyType.equals(MultipartFile[].class)) {
MultipartFile[] file = (MultipartFile[]) object;
if (file != null) {
Map<String, Object> data = Collections.singletonMap(file.length == 0 ? "" : file[0].getName(), object);
super.encode(data, MAP_STRING_WILDCARD, template);
return;
}
}
super.encode(object, bodyType, template);
}
}
三、修改Feign接口(客户端),指定配置文件
@FeignClient(value = "XXX", fallbackFactory = XXX.class, configuration = MultipartSupportConfig.class)