OpenFeign默认不支持文件上传,需要通过引入Feign的扩展包来实现,添加依赖
Maven增加依赖:
<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>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
添加如下配置类:
@Configuration
public class FeignConfiguration {
@Autowired
private ObjectFactory<HttpMessageConverters> messageConverters;
@Bean
public Encoder feignEncoder() {
return new SpringFormEncoder(new SpringEncoder(messageConverters));
}
}
调用方FeignService接口:
@FeignClient("client2")
public interface Client2FeignService {
// PostMapping注解的consumes要设置成MediaType.MULTIPART_FORM_DATA_VALUE,不然会直接报错
@PostMapping(value = "/hello/test", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
// MultipartFile类型前面用@RequestPart注解修饰,不然文件会传输不过去
String test(@RequestPart(value = "file") MultipartFile file);
}
文件接收方Controller:
@RestController
@RequestMapping("/hello")
public class HelloController {
@PostMapping("/test")
String test(@RequestPart(value = "file") MultipartFile file) {
System.out.println(file.getSize());
return "ok";
}
}