Feign多文件上传
昨天某个业务需要在多个微服务间上传多个文件
百度了一下
参考了下面这篇博客,配了解码器
https://blog.csdn.net/ytzzh0726/article/details/79467843
发现一直报如下错误
class java.util.Collections$SingletonMap is not a type supported by this enc
跟进源码看了一下之后发现是因为Header里没有Content-Type
然后在解码器中加了如下代码
public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException {
if (bodyType.equals(MultipartFile.class)) {
//添加请求头
template.header("Content-Type","multipart/form-data");
MultipartFile file = (MultipartFile) object;
Map data = Collections.singletonMap(file.getName(), object);
super.encode(data, MAP_STRING_WILDCARD, template);
} else if (bodyType.equals(MultipartFile[].class)) {
//添加请求头
template.header("Content-Type","multipart/form-data");
MultipartFile[] file = (MultipartFile[]) object;
if (file != null) {
//files是接收方用@RequestPart(value = "files") 接收的参数
Map data = Collections.singletonMap(file.length == 0 ? "" : "files", object);
super.encode(data, MAP_STRING_WILDCARD, template);
}
} else {
super.encode(object, bodyType, template);
}
}
文件上传成功,但是不太优雅
今天看到有人说直接在clint上加上如下注解就能搞定,不过之前的那个业务已经被砍掉了,懒得在搞了,如果大家碰到这个问题可以试一下,如果可以请在下面评论下
@Headers(“Content-Type: multipart/form-data”)//此注解是feign的注解,不是spring的注解