快上网专注成都网站设计 成都网站制作 成都网站建设
成都网站建设公司服务热线:028-86922220

网站建设知识

十年网站开发经验 + 多家企业客户 + 靠谱的建站团队

量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决

SpringCloudFeign的文件上传实现的示例代码

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

创新互联建站专业为企业提供木兰网站建设、木兰做网站、木兰网站设计、木兰网站制作等企业网站建设、网页设计与制作、木兰企业网站模板建站服务,十多年木兰做网站经验,不只是建网站,更提供有价值的思路和整体网络服务。

服务提供方(接收文件)

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

@RestController
public class UploadController {

  @PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
  public String handleFileUpload(@RequestPart(value = "file") MultipartFile file) {
    return file.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)
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客户端来传文件,比如:

@Test
@SneakyThrows
public void testHandleFileUpload() { 
  File file = new File("files/aaa.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(testServiceClient.handleFileUpload(multi));
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。


当前名称:SpringCloudFeign的文件上传实现的示例代码
文章网址:http://6mz.cn/article/iecpph.html

其他资讯