使用Feign怎么实现多文件上传功能
本篇文章为大家展示了使用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 ObjectFactorymessageConverters; @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怎么实现多文件上传功能,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注创新互联行业资讯频道。
网站名称:使用Feign怎么实现多文件上传功能
文章位置:http://ybzwz.com/article/ijjesc.html