Spring Clound Feign实现MultipartFile文件上传

普通的FeignClient直接去调用远程上传文件接口的时候一直抛异常:MissingServletRequestPartException,“Required request part ‘file’ is not present”


解决方案:

在Feign Client中引用配置类FeignConfiguration,在FeignConfiguration中,实例化FeignSpringFormEncoder

注意:FeignClient中注解@PostMapping的produecesconsumes不能少。

feign client

@FeignClient(name = "xxx", configuration = FeignConfiguration.class)
public interface FileClient {

	@PostMapping(value = "/xxxx", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    RestResp> upload(@RequestPart("file") MultipartFile file);

    @PostMapping(value = "/xxxx", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    RestResp> upload(@RequestPart("file") MultipartFile[] files);

}

feign config

@Configuration
public class FeignConfiguration {

    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }

    @Bean
    public Encoder encoder(){
        return new FeignSpringFormEncoder();
    }
}

FeignSpringFormEncoder

public class FeignSpringFormEncoder extends FormEncoder {
    public FeignSpringFormEncoder() {
        this(new Default());
    }

    public FeignSpringFormEncoder(Encoder delegate) {
        super(delegate);
        MultipartFormContentProcessor processor = (MultipartFormContentProcessor)this.getContentProcessor(ContentType.MULTIPART);
        processor.addWriter(new SpringSingleMultipartFileWriter());
        processor.addWriter(new SpringManyMultipartFilesWriter());
    }

    public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException {
        if (bodyType.equals(MultipartFile.class)) {
            MultipartFile file = (MultipartFile) object;
            Map data = Collections.singletonMap(file.getName(), object);
            super.encode(data, MAP_STRING_WILDCARD, template);
            return;
        } else if (bodyType.equals(MultipartFile[].class)) {
            MultipartFile[] file = (MultipartFile[]) object;
            if(file != null) {
                Map data = Collections.singletonMap("file", object);
                super.encode(data, MAP_STRING_WILDCARD, template);
                return;
            }
        } else if (bodyType.equals(File[].class)) {
            File[] file = (File[]) object;
            if (file != null) {
                Map data = Collections.singletonMap("file", object);
                super.encode(data, MAP_STRING_WILDCARD, template);
                return;
            }
        } else if (bodyType.equals(File.class)) {
            File file = (File) object;
            Map data = Collections.singletonMap("file", object);
            super.encode(data, MAP_STRING_WILDCARD, template);
            return;
        }
        super.encode(object, bodyType, template);
    }
}

参考链接:https://github.com/pcan/feign-client-test

你可能感兴趣的:(Java)