Springboot Feign文件上传

服务提供者

@SpringBootApplication
public class FeignUploadFirstApplication {
  @RestController
  public class UploadController {

    @RequestMapping(value = "/uploadFile",method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public String handleFileUpload(@RequestPart(value = "file") MultipartFile file) {
      return file.getOriginalFilename();
    }
  }
  public static void main(String[] args) {
    SpringApplication.run(FeignUploadFirstApplication.class, args);
  }
}

服务消费者

1.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>

2.feign配置类

@Configuration
public class FeignMultipartSupportConfig {
    @Bean
    public Encoder feignFormEncoder() {
        return new SpringFormEncoder();
    }
}

3.feign调用接口 注解中加入配置类

@FeignClient(value = "xxx", configuration = FeignMultipartSupportConfig.class)
public interface IUploadService {
    /**
     * 文件上传
     * @param file 文件
     * @return
     */
    @RequestMapping(value = "upload/uppic", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    ResultModel<String> uppic(@RequestPart(value = "file")MultipartFile file, @RequestParam Map<String,Object> map);

}

4.上传接口

@RestController
public class UploadController {
  @Autowired
   IUploadService uploadService;

  @RequestMapping(value = "/uploadFile",method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
  public String handleFileUpload(@RequestPart(value = "file") MultipartFile file) {
    return uploadService.uppic(file);
  }
}

文件上传 File 转 Multi

FileInputStream fileInputStream = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), ContentType.TEXT_PLAIN.toString(), fileInputStream);
  • 注意:
    1. File 转 MultipartFile 中的第一个参数必须与服务提供者的接口参数一致,即@RequestPart中的value
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值