介绍

解决feign实现微服务间的文件上传出现错误the request was rejected because no multipart boundary was found

引入包

    <!-- Feign进行跨服务传递文件依赖 -->
    <dependency>
        <groupId>io.github.openfeign.form</groupId>
        <artifactId>feign-form</artifactId>
        <version>3.8.0</version>
    </dependency>
    <dependency>
        <groupId>io.github.openfeign.form</groupId>
        <artifactId>feign-form-spring</artifactId>
        <version>3.8.0</version>
    </dependency>

这是Feign拓展包,版本选择:

Requirements The feign-form extension depend on OpenFeign and its
concrete versions:

all feign-form releases before 3.5.0 works with OpenFeign 9.*
versions; starting from feign-form’s version 3.5.0, the module works
with OpenFeign 10.1.0 versions and greater. IMPORTANT: there is no
backward compatibility and no any gurantee that the feign-form’s
versions after 3.5.0 work with OpenFeign before 10.*. OpenFeign was
refactored in 10th release, so the best approach - use the freshest
OpenFeign and feign-form versions.

Notes:

spring-cloud-openfeign uses OpenFeign 9.* till v2.0.3.RELEASE and uses
10.* after. Anyway, the dependency already has suitable feign-form version, see dependency pom, so you don’t need to specify it
separately;

spring-cloud-starter-feign is a deprecated dependency and it always
uses the OpenFeign’s 9.* versions.
需要特别注意 feign-form 和 OpenFeign 版本之间的关系,spring boot 2.0 至少是3.5.0。

服务接口端

@ApiOperation(value = "附件上传")
@PostMapping("/upload/v1")
public AttachmentOutDTO upload(@RequestParam(value = "file") MultipartFile file,
                               @RequestParam(value = "module", required = false) String module) {
     							//附件上传业务
}

Feign调用端

@Component
@FeignClient(value = "service-file", path = "/api/attachment", fallback = AttachmentClientHystrix.class, configuration = MultipartSupportConfig.class)
public interface AttachmentClient {
    /**
     * 附件上传
     *
     * @param file
     * @param module
     * @return
     */
    @PostMapping(value = "/upload/v1", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    AttachmentOutDTO upload(@RequestPart(value = "file") MultipartFile file,
                            @RequestParam(value = "module", required = false) String module);
}

配置端

@Configuration
public class MultipartSupportConfig {

    @Autowired
    private ObjectFactory<HttpMessageConverters> messageConverters;

    @Bean
    public Encoder feignFormEncoder(){
        return new SpringFormEncoder(new SpringEncoder(messageConverters));
    }

}

特别注意:

  1. consumes = MediaType.MULTIPART_FORM_DATA_VALUE必须有

  2. 文件部分注解为@RequestPart,要不然出现错误:the request was rejected because no
    multipart boundary was found

  3. MultipartSupportConfig 不可以少。

参考:https://blog.csdn.net/y526089989/article/details/97762675

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐