【已解决】Spring Cloud Feign 上传文件,提示:the request was rejected because no multipart boundary was found的问题

时间:2025-04-11 17:12:41

我在网上查了很多关于 Spring Cloud 文件上传的相关资料也花费了不少时间,根据他们提供的方案修改也没有得到解决,经过自己探讨与摸索,终于解决了我的问题,也与大家分享了下,如下:

一、项目结构

首先介绍一下项目结构,我们开发的项目结构比较简单

xxx-api工程:这个工程主要是对外提供接口.

service-xxx工程:这个工程承载核心业务处理服务

二、上代码

对于开发者来说,看代码比较实在,如下:

xxx-api工程下的文件上传相关代码:

1、xxx-api项目的 Controller类  至关重要的 @RequestPart 注解

    @PostMapping(path = "/uploadImg")
    public Result<String> uploadImg(@RequestPart("file") MultipartFile file, @RequestHeader String accessToken) {
        Resp result = (accessToken);
        if (() > -1) {
            String accountId = (()).get("account").toString();
            return (file, accountId);
        } else {
            return ("获取用户信息失败,请重新尝试");
        }
    }

2、FeginClient类 注意标注 @PostMapping(path = "/api/file/uploadImg",consumes = MediaType.MULTIPART_FORM_DATA_VALUE) 和 @RequestPart 注解

/**
     * @param file      文件
     * @param accountId 用户唯一ID
     * @return 结果说明
     */
    @PostMapping(path = "/api/file/uploadImg",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    Result<String> uploadImg(@RequestPart("file") MultipartFile file, @RequestParam String accountId);

二、service-xxx 工程,如下: 至关重要的 @RequestPart 注解

    @PostMapping(path = "/uploadImg")
    public Result<String> uploadImg(@RequestPart("file") MultipartFile file,@RequestParam String accountId) throws Exception {
        if (()) {
            return ("没有要上传的文件");
        }
        BufferedImage image = (());
        if (image == null) {
            return ("文件错误");
        }
        byte[] imageInByte = (image);
        String name = "";
        String fileName = ().substring(0, ().lastIndexOf('.'));
        if (fileName != null && !("")) {
            name = fileName;
        }
        return ((name + ".jpg", accountId, imageInByte));
    }

总结一下:

        对于文件类微服务的调用,要用 @RequestPart 注解标注,在合适位置配合注解 @PostMapping(path = "/api/file/uploadImg",consumes =MediaType.MULTIPART_FORM_DATA_VALUE) 进行 修饰使用,否则会报资源类型和其他的一些问题。