Feign 接口上传文件

1)Encoder 配置注入容器

Feign 接口上传文件

2)

public class SpringFormEncoderExtension extends FormEncoder {

    /**
     * 使用默认的feign编码器
     *
     * @author*/
    public SpringFormEncoderExtension() {
        this(new Default());
    }

    /**
     * 使用传入的编码器并提供对多文件的支持
     *
     * @param encoder 编码器
     * @author*/
    public SpringFormEncoderExtension(Encoder encoder) {
        super(encoder);

        MultipartFormContentProcessor processor = (MultipartFormContentProcessor) getContentProcessor(ContentType.MULTIPART);
        processor.addWriter(new SpringSingleMultipartFileWriter());
        processor.addWriter(new SpringManyMultipartFilesWriter());
    }

    /**
     * 模仿FormEncode对其进行扩展支持多文件传递
     *
     * @param object   传递内容
     * @param bodyType 传递类型
     * @param template 传递路径
     * @author*/
    @Override
    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);
        } else if (bodyType.equals(MultipartFile[].class)) {
            MultipartFile[] file = (MultipartFile[]) object;
            if (file != null) {
                Map data = Collections.singletonMap(file.length == 0 ? "" : file[0].getName(), object);
                super.encode(data, MAP_STRING_WILDCARD, template);
            }
        } else {
            super.encode(object, bodyType, template);
        }
    }
}

 

3)

@FeignClient(name = "storage-service", fallback = UploadFeignClientFallback.class, configuration = FeignConfig.class)
public interface UploadFeignClient {

    @PostMapping(value = "/storage/upload/goods/{serverName}/{shopId}",produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}
            , consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    Map uploadGoods(@RequestPart("file") MultipartFile file, @PathVariable("serverName") String serverName
    , @PathVariable("shopId") String shopId);
}

 


上一篇:MyBatis + MySQL + MultipartFile保存文件二进制数据到表里面


下一篇:解决使用Spring Boot、Multipartfile上传文件路径错误问题