本篇文章为大家展示了使用Feign怎么实现多文件上传功能,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
想用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); }
上述内容就是使用Feign怎么实现多文件上传功能,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。