Feign传输Multipartfile文件的正确方式,Current request is not a multipart request报错解决

一、错误的方式

例如,我们在子服务A的controller中,有一个接收Multipartfile文件的POST请求接口,通常写成如下方式

    @PostMapping("/upload")
    public String upload(
            @RequestParam("pic") MultipartFile pic,
            @RequestParam("otherparam") String otherParam
    ) throws Exception{
        //.....
        
        return "success";
    }

现在子服务B需要调用A服务上面的接口,在feign中发送file时,很多人习惯写成下面样子

    @PostMapping("/service_a/upload")
    String upload(
            @RequestParam("pic") MultipartFile pic,
            @RequestParam("otherparam") String otherParam
    ) throws Exception;

发送请求后,在服务A的控制台,可以看到报错日志如下

org.springframework.web.multipart.MultipartException:Current request is not a multipart request.......

 

二、正确方式

由上可知,报错提示当前请求不是一个 multipart request

原因是在feign中,发送 multipartfile文件,应该使用【@RequestPart】而不是【@RequestParam】,且需要设置请求content-type为【multipart/form-data】,所以正确写法如下

    //正确方式
    @PostMapping(value = "/service_a/upload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    String upload2(
            @RequestPart("pic") MultipartFile pic,
            @RequestParam("otherparam") String otherParam
    ) throws Exception;

 

 

 


版权声明:本文为weishaoqi2原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。