spring同时接收文件参数MultipartFile和json参数,并通过feign转发参数到其他服务

spring controller同时接口文件参数和json入参,并将这些参数通过feign请求到其他微服务。RPC调用通过springcloud实现。

示例:服务1:provider1,服务2:provider2

provider1代码示例:

controller接收参数示例:

import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

@Slf4j
@RestController
@RequestMapping("/xxx")
public class MyController {
 @RequestMapping("/reqFile")
    public Object uploadFile(MultipartFile file, @ModelAttribute CommonReq req) 
    {
        // xxx逻辑
        
        // do feign
       xxx.feign(file, req);
       
    }
}

feign调用示例

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import feign.hystrix.FallbackFactory;

@FeignClient(value = "provider2", fallbackFactory = MyFeignFallbackFactory.class)
public interface MyFeign {


    @PostMapping(value = "/xxx", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
   Resp  feign(@RequestPart("file") MultipartFile file, @RequestPart("req")CommonReq req);
}

提示

我这里使用的springboot版本2.5.14,但上传文件的时候之前uploadFile方法的file参数接收文件一直为null,然后再yml文件里面加上这行配置之后就可以接收到文件了,但是没太搞懂为什么

spring:
  mvc:
    hiddenmethod:
      filter:
        enabled: true

provider2接收feign请求示例

controller接收示例:

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@RestController
@RequestMapping("/xxx")
public class Provider2Controller {
   @PostMapping("/xxx")
    public Object feignFile(@RequestPart("file") MultipartFile file, @RequestPart("req") String req){
       // xxx逻辑
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容