首页 > 其他分享 >SpringCloud 使用feign进行文件MultipartFile传输

SpringCloud 使用feign进行文件MultipartFile传输

时间:2024-03-21 14:55:20浏览次数:25  
标签:feign agencyId SpringCloud springframework import org MultipartFile com

SpringCloud组件fiegn默认是不支持传递文件的。但是提供了feign-form扩展工具

解决方法:

步骤一:在消费者服务中加入相关pom依赖。

<!--解决SpringCloud 组件feign默认是不支持传递文件的-->
        <dependency>
            <groupId>io.github.openfeign.form</groupId>
            <artifactId>feign-form-spring</artifactId>
            <version>3.6.0</version>
        </dependency>
        <dependency>
            <groupId>io.github.openfeign.form</groupId>
            <artifactId>feign-form</artifactId>
            <version>3.6.0</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>

步骤二:编写一个配置类

 

package com.ckfuture.springcloud.config;

import feign.Logger;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;


/**
 * 解决feign文件传递问题的配置类
 */
@Configuration
public class FeignMultipartSupportConfig {
    @Autowired
    private ObjectFactory<HttpMessageConverters> messageConverters;
    @Bean
    @Primary
    @Scope("prototype")
    public Encoder multipartFormEncoder(){
        return new SpringFormEncoder(new SpringEncoder(messageConverters));
    }
    @Bean
    public feign.Logger.Level multipartLoggerLevel(){
        return feign.Logger.Level.FULL;
    }

}

步骤三:feign接口的编写。服务调用方加注解类(配置类)

 

package com.ckfuture.springcloud.deliveryman.service;

import com.alibaba.fastjson.JSONObject;
import com.ckfuture.springcloud.config.FeignMultipartSupportConfig;
import com.ckfuture.springcloud.utils.Result;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


/**
 * @description: 消费者-信息服务接口
 * @author: CKFuture
 * @since: 2024-03-19 13:24
 * @version: v1.0
 * @LastEditTime:
 * @LastEditors:
 * @copyright: hrbckfuture.com
 */
@FeignClient(value = "${service-url.nacos-user-service}",configuration = FeignMultipartSupportConfig.class)//解决feign文件传递问题的配置类feign配置类
public interface IDeliverymanService {

   

    /**
     * 批量添加信息
     * @param excelFile
     * @param agencyId
     * @return
     */
    @PostMapping(value = "/deliveryman/uploadExcel", consumes = {"multipart/form-data"})//“multipart/form-data”指定类型
    public Result uploadExcel(
            @RequestPart("excelFile") MultipartFile excelFile,
            @RequestParam(value = "agencyId", required = true) Integer agencyId
    ) throws IOException;

}

步骤四:修改消费者提供的服务提供类@RequestPart 来接收文件参数

package com.ckfuture.springcloud.deliveryman.controller;

import com.alibaba.fastjson.JSONObject;
import com.ckfuture.springcloud.deliveryman.service.IDeliverymanService;
import com.ckfuture.springcloud.utils.Result;
import io.swagger.annotations.Api;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import org.springframework.http.MediaType;

import java.io.IOException;


/**
 * @descrption: 消费者-信息控制器
 * @author: CKFuture
 * @since: 2024-03-19 13:35
 * @version: v1.0
 * @LastEditTime:
 * @LastEditors:
 * @copyright: hrbckfuture.com
 */
@Api(tags={"基础管理/信息接口"})
@RestController
public class DeliverymanController {
    @Resource
    private IDeliverymanService service;

  
    /**
     * 批量添加信息
     * @param excelFile
     * @param agencyId
     * @return
     */
    @PostMapping(value = "/deliveryman/uploadExcel",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result uploadExcel(
            @RequestPart("excelFile") MultipartFile excelFile,
            @RequestParam(value = "agencyId", required = true) Integer agencyId
    ){
        try{
            System.out.println("我被调用了!");
            return service.uploadExcel(excelFile,agencyId);
        }catch (Exception ex){
            System.out.println(ex.getMessage());
            return Result.failure(1,"error");
        }
    }

}

注意点:文件流要用RequestPart注解传参数,其余参数用RequestParam注解传参。

步骤五:生产者提供服务

   /**
     * 生产者-批量添加信息
     * @param excelFile
     * @param agencyId
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/deliveryman/uploadExcel", consumes = {"multipart/form-data"})
    @ResponseBody
    public Result uploadExcel(
            @RequestParam("excelFile") MultipartFile excelFile,
            @RequestParam(value = "agencyId", required = true) Integer agencyId
    ) throws IOException {
        try {
            //逻辑代码

        } catch (Exception ex) {
            return Result.failure(ResponseCode.ERROR, ResponseMsg.QUERY_ERROR);
        }
    }

 

 

本文引用:https://blog.csdn.net/qq_52211542/article/details/129779344

标签:feign,agencyId,SpringCloud,springframework,import,org,MultipartFile,com
From: https://www.cnblogs.com/ckfuture/p/18087388

相关文章

  • 【OpenFeign】@FeignClient 注入过程源码分析
    1 前言微服务之间的调用,OpenFeign是一种选择,并且还提供了很多功能,比如我们有多个节点,它能负载均衡,当服务发生异常时,它还能提供熔断机制。所以它是怎么实现的,因为我们平时只需要写@FeignClient是个接口,所以它势必会走代理,所以是不是要从我们的@FeignClient 下手。那么这节......
  • feign设置超时时间
    feign设置超时时间feign的本质是调用http请求,如果不设置超时时间,请求长时间连接着,占用系统资源,影响用户体验。feign设置超时时间,可以通过Request.Options来设置。FeignClientFactoryBean:调用feign,会调用FeignClientFactoryBean类的feign()方法,再用configureFeig......
  • 使用AOP记录feign调用日志
    文章目录业务场景使用DemoClientFeignDemlFeignFallBack主要代码DockLogAspectDockLogDockLogServiceDockLogAddDTOJacksonUtils业务场景记录请求第三方接口的情况。@DockLog可以用在类上也可以用在方法上使用DemoClientFeignimportorg.springframework.cloud......
  • 利用ssh隧道提升 feign 调用开发效率
    问题描述springcloud架构下,微服务间很多是通过feign进行调用的。作为一家小公司,很多微服务在开发环境没有部署实例,这就导致,想在本地做开发调试,要花精力起很多依赖服务。耗时费力。解决办法1、利用ssh隧道,让办公网可以访问测试环境(阿里云、默认不开放端口)的微服务。ssh-f......
  • feigni请求添加拦截器
    @FeignClient的configuration属性:Feign注解@FeignClient的configuration属性,可以对feign的请求进行配置。包括配置Feign的Encoder、Decoder、Interceptor等。feign请求添加拦截器,也可以通过这个configuration属性来指定。feign请求拦截器RequestIntercept......
  • Gateway过滤器中调用OpenFeign时出现循环依赖问题
    为了保证JWT随机生成的密钥一致,我设计了一个token服务,专门获取JWT,和生成token。在网关使用client调用服务时,出现了bean循环依赖Thedependenciesofsomeofthebeansintheapplicationcontextformacycle:┌─────┐|gateWayGlobalFilterdefinedinfile[C:\Us......
  • 第四章-OpenFeign 远程调用
    第四章SpringCloudOpenFeign在第二章中,我们通过RestTemplate实现了远程调用:@AutowiredprivateDiscoveryClientdiscoveryClient;privateStringgetLoadBalancedServerAddress(){List<ServiceInstance>instances=discoveryClient.getInstances("depart-......
  • 基于springcloud实现鲜花订购网微服务演示【附项目源码】
    基于springcloud实现鲜花订购网微服务演示JAVA简介Java主要采用CORBA技术和安全模型,可以在互联网应用的数据保护。它还提供了对EJB(EnterpriseJavaBeans)的全面支持,javaservletAPI,JSP(javaserverpages),和XML技术。Java是一种计算机编程语言,具有封装、继承和多态性三个......
  • 微服务分布式springcloud研究生志愿填报辅助系统
    本文讲述了研究生志愿填报辅助系统。结合电子管理系统的特点,分析了研究生志愿填报辅助系统的背景,给出了研究生志愿填报辅助系统实现的设计方案。本论文主要完成不同用户的权限划分,不同用户具有不同权限的操作功能,在用户模块,主要有用户进行注册和登录,用户可以实现查看院校信息......
  • feign传递token
    publicclassFeignInterceptorimplementsRequestInterceptor{@Overridepublicvoidapply(RequestTemplaterequestTemplate){ServletRequestAttributesrequestAttributes=(ServletRequestAttributes)RequestContextHolder.getRequestAttributes();if(req......