avatar

Feign实现多文件上传

想用Feign实现多文件的批量上传
Controller实现如下代码:

1
2
3
4
5
6
7
8
@PostMapping(value = "/uploadBatch/ali", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, headers = "content-type=multipart/form-data")
@ApiOperation(value = "阿里云批量上传文件")
@ResponseBody
public Response uploadBatchAli(
@RequestPart("files") MultipartFile[] files,
@RequestParam("path") String path) {
return fileServiceClient.uploadBatchAli(files, path);
}

FeignClient代码如下

1
2
3
4
@PostMapping(value = File_Service_API_PREFIX + "/uploadBatch/ali", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
Response uploadBatchAli(
@RequestPart("files") MultipartFile[] files,
@RequestParam("path") String path);

Feign调用服务,传送类似MultipartFile[] files的时候,会出现如下错误

1
Could not write request: no suitable HttpMessageConverter found for request type [[Lorg.springframework.web.multipart.MultipartFile;] and content type [multipart/form-data]"

错误是因为Feign在组装MultipartFile[] files,的时候出现了问题
,解决这个问题可以重写SpringFormEncoder这个类,重写后的代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class SpringMultipartEncoder extends SpringFormEncoder {
public SpringMultipartEncoder(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 != null && 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);
return;
}
}
super.encode(object, bodyType, template);
}
}

然后配置类如下:

1
2
3
4
5
6
7
8
9
10
@Configuration
public class MultipartSupportConfig {

@Autowired
private ObjectFactory<HttpMessageConverters> messageConverters;

@Bean
public Encoder feignFormEncoder() {
return new SpringMultipartEncoder(new SpringEncoder(messageConverters));
}

然后FeignClient指定一下调用类

1
2
3
4
5
6
7
8
9
10
@FeignClient(name = "xxx",
configuration = MultipartSupportConfig.class)
public interface FileServiceClient {

@PostMapping(value = File_Service_API_PREFIX + "/uploadBatch/ali", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
Response uploadBatchAli(
@RequestPart("files") MultipartFile[] files,
@RequestParam("path") String path);

}

Ok,到此就算配置完成了。Feign完美支持多文件上传。

文章作者: 无知的小狼
文章链接: https://bytedance.press/2021/04/18/20210401/Feign%E5%AE%9E%E7%8E%B0%E5%A4%9A%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 无知的小狼

评论