Spring Cloud Feign上传文件

Feign 无法直接传递文件参数,需要在client端引入几个依赖

1. 创建服务端

方式与普通的文件上传方法一致

@RestController
@RequestMapping("/producer/upload")
class UploadProducer {

    @PostMapping(value = '/upload', consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    String upload(@RequestPart(value = "file") MultipartFile file) {
        // ...
        return file.originalFilename
    }
}

2. 创建client

2.1 需要在客户端引入以下依赖

io.github.openfeign.form:feign-form:3.0.3
io.github.openfeign.form:feign-form-spring:3.0.3

2.2 定义client接口

@FeignClient(name = 'upload', url = '${upload.base-url}', path = '/producer/upload')
interface UploadClient {

    @RequestMapping(value = '/upload', method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE
            , produces = MediaType.APPLICATION_JSON_VALUE)
    String upload(@RequestPart("file") MultipartFile file)
}

2.3 添加配置文件

划重点

@Configuration
class MultipartSupportConfig {
    @Autowired
    private ObjectFactory messageConverters

    // new一个form编码器,实现支持form表单提交
    @Bean
    Encoder feignFormEncoder() {
        return new SpringFormEncoder(new SpringEncoder(messageConverters))
    }
}

3. 创建Controller,调用client接口

@RestController
@RequestMapping("/")
class RecordController {
    @Autowired
    private UploadClient uploadClient

    @RequestMapping(value = '/upload', method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    String upload(@RequestParam("file") MultipartFile file) {
        return uploadClient.uploade(file)
    }
}   

你可能感兴趣的:(Feign)