SpringCloudFeign多文件上传

前言

Java学习路线个人总结-博客
❤欢迎点赞👍收藏⭐留言 📝分享给需要的小伙伴

SpringCloudFeign多文件上传

Feign多文件上传

POM依赖

<!--文件上传配置-->
<dependency>
    <groupId>io.github.openfeign.form</groupId>
    <artifactId>feign-form</artifactId>
    <version>3.0.3</version>
</dependency>

<dependency>
    <groupId>io.github.openfeign.form</groupId>
    <artifactId>feign-form-spring</artifactId>
    <version>3.0.3</version>
</dependency>

Fiegn接口端

配置类

/**
 * <p>文件上传配置</p>
 *
 * @author: 
 */
public class FeignFormEncoder extends FormEncoder {

    /**
     * Constructor with the default Feign's encoder as a delegate.
     */
    public FeignFormEncoder() {
        this(new Default());
    }


    /**
     * Constructor with specified delegate encoder.
     *
     * @param delegate delegate encoder, if this encoder couldn't encode object.
     */
    public FeignFormEncoder(Encoder delegate) {
        super(delegate);

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


    @Override
    public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException {
        if (bodyType.equals(MultipartFile.class)) {
            MultipartFile file = (MultipartFile) object;
            super.encode(singletonMap(file.getName(), object), MAP_STRING_WILDCARD, template);
            return;
        } else if (bodyType.equals(MultipartFile[].class)) {
            MultipartFile[] file = (MultipartFile[]) object;
            if (file != null) {
                super.encode(singletonMap(file.length == 0 ? "" : file[0].getName(), object), MAP_STRING_WILDCARD, template);
                return;
            }
        }
        super.encode(object, bodyType, template);
    }
}

Feign接口

/**
 * <p>文件Feign接口</p>
 */
@FeignClient(value = "xxxxx-file", configuration = FileFeignClient.MultipartSupportConfig.class)
public interface FileFeignClient {

    /**
     * <p>文件上传</p>
     */
    @RequestMapping(value = "/file/api/v1/files", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    List<Map<String, String>> handleFileUpload(@RequestPart(value = "file", required = false) MultipartFile[] files,);


    /**
     * <p>多文件上传表单编码配置</p>
     *
     */
    @Configuration
    class MultipartSupportConfig {

        @Autowired
        private ObjectFactory<HttpMessageConverters> messageConverters;

        @Bean
        @Primary
        @Scope("prototype")
        public Encoder feignFormEncoder() {
            return new FeignFormEncoder(new SpringEncoder(messageConverters));
        }
    }

}

接口提供端

	@PostMapping(value = "/file/api/v1/files", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
  	@ResponseBody
  	public List<Map<String,String>> handleFileUpload(@RequestPart(value = "file",required=false) MultipartFile[] files
    ) throws Exception {
        //具体代码就不给大家写了,采用这种方式可以接到文件的数组
    }

接口消费端

@PostMapping(value = "/aa",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
 public List<Map<String, String>> aaa(@RequestPart(value = "file") MultipartFile[] files) {
        List<Map<String, String>> maps = fileFeignClient.handleFileUpload(files);
        return maps;
    }

在代码中调用Feign多文件上传,上面代码不需要改变

如遇到在代码里面去调用文件上传的Feign接口怎么处理呢,不要慌,因为我之前在工作中也遇到了。

在消费方也就是调用方POM添加依赖

<!--如遇到在代码中多文件上传,需要用到FileItem -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>

消费方代码

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;

@PostMapping(value = "/aa",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
 public List<Map<String, String>> aaa(@RequestPart(value = "file") MultipartFile[] files) {
         //生命MultipartFile数组
        MultipartFile [] files  = new MultipartFile[1];
        File file = new File("D:\\壁纸\\timg.jpg");

        //得到FileItem
        FileItem fileItem = createFileItem(file, file.getName());
        //获得MultipartFile
        MultipartFile mfile = new CommonsMultipartFile(fileItem);
        //放进数组
        files[0] = mfile;
     
        List<Map<String, String>> maps = fileFeignClient.handleFileUpload(files);
        return maps;
    }


//获得FileItem方法
private FileItem createFileItem(File file, String fieldName) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        //file 接收参数名称    ContentType    isFormField是否是表单参数   文件名称
        FileItem item = factory.createItem("file", ContentType.MULTIPART.getHeader(), true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

冒险的梦想家

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值