Feign使用MultipartFile

本文介绍了如何在Feign客户端和服务器端使用MultipartFile进行文件上传,包括依赖配置、FeignClient的编码器设置以及服务提供者和消费者的实现方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Feign的方法参数使用MultipartFile

Feign的方法参数使用MultipartFile,不能直接用,需要做一些配置。

依赖包:

<dependency>
    <groupId>io.github.openfeign.form</groupId>
    <artifactId>feign-form</artifactId>
    <version>3.8.0</version>
</dependency>
<dependency>
    <groupId>io.github.openfeign.form</groupId>
    <artifactId>feign-form-spring</artifactId>
    <version>3.8.0</version>
</dependency>

或者是直接用 spring-cloud-starter-openfeign。

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

服务提供者

MultipartFile 使用 @RequestPart 修饰。

还需要添加一个消费者类型:consumes = MediaType.MULTIPART_FORM_DATA_VALUE

@RestController
@RequestMapping("/xx")
public class FileController {

    @PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Response uploadFile(@RequestPart("file") MultipartFile multipartFile, @RequestParam("name") String name) {
       
        //....
    }
}

配置Feign的Encoder

@Configuration
public class FeignMultipartConfig {

    @Autowired
    private ObjectFactory<HttpMessageConverters> messageConverters;

    @Bean
    @Primary
    @Scope("prototype")
    public Encoder feignEncoder() {
        return new SpringFormEncoder(new SpringEncoder(messageConverters));
    }
}

FeignClient

FeignClient 指定 configuration = FeignMultipartConfig.class

consumes = MediaType.MULTIPART_FORM_DATA_VALUE

如下所示。

@FeignClient(name = "xx",configuration = FeignMultipartConfig.class)
@RequestMapping("/xx")
public interface FeignService {

    @PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    Response uploadFile(@RequestPart("file") MultipartFile multipartFile, @RequestParam("name") String name);

}

服务消费者

MultipartFile用 @RequestPart 修饰即可。

@RestController
@Slf4j
public class FeignController {

    @Autowired
    private FeignService feignService;

    @RequestMapping(value = "/uploadFile")
    public String fileUpload(@RequestPart("file") MultipartFile file, @RequestParam("name") String name ) {

        log.info("文件上传---fileName---{}",file.getOriginalFilename());
        return feignService.uploadFile(file,name);
    }

}

参考资料:

https://www.cnblogs.com/geekdc/p/13685039.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值