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));
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短