Spring Cloud Feign文件上传(File及MultipartFile)

Spring Cloud Feign文件上传(File及MultipartFile)

说明

当使用Spring Cloud Feign需要上传文件分两种情况:一种是前端上传到微服务,微服务调用Feign接口将MultipartFile上传到另一个微服务;另一种是微服务上传File对象到另一个微服务。

MultipartFile文件上传

这种最简单,只需要提供一个@Bean SpringEncoder即可,然后定义Feign接口即可完成

@Configuration
public class FeignConfig {
    @Bean
    public SpringEncoder springEncoder(ObjectFactory<HttpMessageConverters> messageConverters) {
        return new SpringEncoder(messageConverters);
    }
}

编写Feign接口样例

@FeignClient(value = "common-service", fallbackFactory = FeignFallbackFactory.class)
public interface OssRemoteService {
    /**
     * 上传文件
     *
     * @param file    MultipartFile文件
     * @return 上传结果
     */
    @PostMapping(value = "/oss/upload/{bucket}/{autoAck}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    XCloudResponse<OssUploadResponse> upload(@RequestPart("file") MultipartFile file);
}

File对象上传

某些时候需要微服务本地生成海报File对象,调用文件上传服务上传。此时需要扩展SpringEncoder,将File转换成MultipartFile,如FeignSpringFormEncoder#encode,判定bodyType,将File对象转换为ByteArrayMultipartFile(实现接口MultipartFile)

@Component
public class FeignSpringFormEncoder extends SpringEncoder {
    public FeignSpringFormEncoder(ObjectFactory<HttpMessageConverters> messageConverters) {
        super(messageConverters);
    }

    @Override
    public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException {
        if (Util.MAP_STRING_WILDCARD == bodyType) {
            Map<String, Object> objectMap = (Map<String, Object>) object;
            String path = (String)objectMap.get("file");
            File file = new File(path);
            if (!file.exists()) {
                throw new IllegalArgumentException("文件不存在:" + path);
            }
            objectMap.put("file", new ByteArrayMultipartFile(file));
        }

        super.encode(object, bodyType, template);
    }
}

ByteArrayMultipartFile源码如下

@Data
public class ByteArrayMultipartFile implements MultipartFile {
    private final String name;
    private final String originalFilename;
    private final String contentType;
    private final byte[] bytes;

    public boolean isEmpty() {
        return this.bytes.length == 0;
    }

    public long getSize() {
        return this.bytes.length;
    }

    public InputStream getInputStream() {
        return new ByteArrayInputStream(this.bytes);
    }

    public void transferTo(File destination) throws IOException {
        try (FileOutputStream outputStream = new FileOutputStream(destination)) {
            outputStream.write(this.bytes);
        }
    }

    public ByteArrayMultipartFile(String name, String originalFilename, String contentType, byte[] bytes) {
        if (bytes == null) {
            throw new NullPointerException("bytes is marked @NonNull but is null");
        } else {
            this.name = name;
            this.originalFilename = originalFilename;
            this.contentType = contentType;
            this.bytes = bytes;
        }
    }

    public ByteArrayMultipartFile(File file) {
        this.name = file.getName();
        this.originalFilename = file.getName();
        this.contentType = new MimetypesFileTypeMap().getContentType(file);
        try (FileInputStream fis = new FileInputStream(file)) {
            this.bytes = IOUtils.toByteArray(fis);
        } catch (Exception e) {
            throw new IllegalArgumentException("文件内容读取失败!");
        }
    }
}

至此已经可以实现File对象上传,编写Feign接口样例如下

@FeignClient(value = "common-service", fallbackFactory = FeignFallbackFactory.class)
public interface OssRemoteService {
    /**
     * 上传文件
     *
     * @param file    MultipartFile文件
     * @return 上传结果
     */
    @PostMapping(value = "/oss/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    XCloudResponse<OssUploadResponse> upload(@RequestPart("file") MultipartFile file);
	/**
     * 上传文件
     *
     * @param file   file文件
     * @return 上传结果
     */
    @PostMapping(value = "/oss/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    XCloudResponse<OssUploadResponse> upload(@RequestPart("file") File file);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值