您现在的位置是:首页 > 文章详情

java B2B2C 仿淘宝电子商城系统-Spring Cloud Feign的文件上传实现

日期:2019-04-17点击:485

在Spring Cloud封装的Feign中并不直接支持传文件,但可以通过引入Feign的扩展包来实现,本文就来具体说说如何实现。

服务提供方(接收文件)

服务提供方的实现比较简单,就按Spring MVC的正常实现方式即可,比如:

@EnableFeignClients @EnableDiscoveryClient @SpringBootApplication public class Application { @RestController public class UploadController { @PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public String handleFileUpload(@RequestPart(value = "file") MultipartFile file) { return file.getName(); } } public static void main(String[] args) { new SpringApplicationBuilder(Application.class).web(true).run(args); } }

服务消费方(发送文件)

在服务消费方由于会使用Feign客户端,所以在这里需要在引入feign对表单提交的依赖,具体如下:

<dependency> <groupId>io.github.openfeign.form</groupId> <artifactId>feign-form</artifactId> <version>3.0.3</version> </dependency> <dependency> <groupId>io.github.openfeign.form</groupId> <artifactId>feign-form-spring</artifactId> <version>3.0.3</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency>

定义文件上传方的应用主类和FeignClient,假设服务提供方的服务名为 eureka-feign-upload-server

@EnableFeignClients @EnableDiscoveryClient @SpringBootApplication public class Application { public static void main(String[] args) { new SpringApplicationBuilder(Application.class).web(true).run(args); } } @FeignClient(value = "upload-server", configuration = UploadService.MultipartSupportConfig.class) public interface UploadService { @PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) String handleFileUpload(@RequestPart(value = "file") MultipartFile file); @Configuration class MultipartSupportConfig { @Bean public Encoder feignFormEncoder() { return new SpringFormEncoder(); } } }

在启动了服务提供方之后,尝试在服务消费方编写测试用例来通过上面定义的Feign客户端来传文件,比如:

@Slf4j @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest public class UploadTester { @Autowired private UploadService uploadService; @Test @SneakyThrows public void testHandleFileUpload() { File file = new File("upload.txt"); DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file", MediaType.TEXT_PLAIN_VALUE, true, file.getName()); try (InputStream input = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()) { IOUtils.copy(input, os); } catch (Exception e) { throw new IllegalArgumentException("Invalid file: " + e, e); } MultipartFile multi = new CommonsMultipartFile(fileItem); log.info(uploadService.handleFileUpload(multi)); } }

java B2B2C 仿淘宝电子商城系统

原文链接:https://yq.aliyun.com/articles/698730
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章