Spring Cloud Feign的文件上传实现的示例代码
在SpringCloud封装的Feign中并不直接支持传文件,但可以通过引入Feign的扩展包来实现,本来就来具体说说如何实现。
服务提供方(接收文件)
服务提供方的实现比较简单,就按SpringMVC的正常实现方式即可,比如:
@RestController
publicclassUploadController{
@PostMapping(value="/uploadFile",consumes=MediaType.MULTIPART_FORM_DATA_VALUE)
publicStringhandleFileUpload(@RequestPart(value="file")MultipartFilefile){
returnfile.getName();
}
}
服务消费方(发送文件)
在服务消费方由于会使用Feign客户端,所以在这里需要在引入feign对表单提交的依赖,具体如下:
io.github.openfeign.form feign-form 3.0.3 io.github.openfeign.form feign-form-spring 3.0.3 commons-fileupload commons-fileupload
定义FeignClient,假设服务提供方的服务名为upload-server
@FeignClient(value="upload-server",configuration=TestServiceClient.MultipartSupportConfig.class)
publicinterfaceUploadService{
@PostMapping(value="/uploadFile",consumes=MediaType.MULTIPART_FORM_DATA_VALUE)
StringhandleFileUpload(@RequestPart(value="file")MultipartFilefile);
@Configuration
classMultipartSupportConfig{
@Bean
publicEncoderfeignFormEncoder(){
returnnewSpringFormEncoder();
}
}
}
在启动了服务提供方之后,尝试在服务消费方编写测试用例来通过上面定义的Feign客户端来传文件,比如:
@Test
@SneakyThrows
publicvoidtestHandleFileUpload(){
Filefile=newFile("files/aaa.txt");
DiskFileItemfileItem=(DiskFileItem)newDiskFileItemFactory().createItem("file",
MediaType.TEXT_PLAIN_VALUE,true,file.getName());
try(InputStreaminput=newFileInputStream(file);OutputStreamos=fileItem.getOutputStream()){
IOUtils.copy(input,os);
}catch(Exceptione){
thrownewIllegalArgumentException("Invalidfile:"+e,e);
}
MultipartFilemulti=newCommonsMultipartFile(fileItem);
log.info(testServiceClient.handleFileUpload(multi));
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语