Feign使用MultipartFile

Feign的方法参数使用MultipartFile

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

依赖包:


    io.github.openfeign.form
    feign-form
    3.8.0


    io.github.openfeign.form
    feign-form-spring
    3.8.0


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


    org.springframework.cloud
    spring-cloud-starter-openfeign


服务提供者

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

你可能感兴趣的:(feign,java,后端)