想用Feign实现多文件的批量上传 Controller实现如下代码:
@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代码如下
@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的时候,会出现如下错误
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这个类,重写后的代码如下
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);
}
}
然后配置类如下:
@Configuration
public class MultipartSupportConfig {
@Autowired
private ObjectFactory<HttpMessageConverters> messageConverters;
@Bean
public Encoder feignFormEncoder() {
return new SpringMultipartEncoder(new SpringEncoder(messageConverters));
}
然后FeignClient指定一下调用类
@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完美支持多文件上传。