您好,登錄后才能下訂單哦!
本篇文章為大家展示了使用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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。