springboot 版本号:2.1.13-RELEASE

springcloud 版本 :Greenwich.SR6

openfeign 引入的包是

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

版本号自动从父pom中继承,springcloud已经集合了这个openfeign的版本

服务端代码:主要就是文件参数的注解使用的@RequestPar 还有就是@postmapping 注解中有consumer值要是{MediaType.MULTIPART_FORM_DATA_VALUE}

   @PostMapping(path = "/uploadFileByMultipartFile",consumes= {MediaType.MULTIPART_FORM_DATA_VALUE})
    public BaseResult<Boolean> uploadFileByMultipartFile(@RequestParam("bucketName") String bucketName,@RequestParam("fileName") String fileName, @RequestPart("uploadFile") MultipartFile file){
        try {
            return fileSystemService.uploadFileByMultipartFile(bucketName, fileName, file);
        }catch (Exception e){
            return BaseResult.fail("上传文件异常");
        }

    }

并且服务端的yml文件中要配置,这里要上传最大文件的大小,我就是因为这里没有配置导致我的大文件一直上传失败,我还以为是openfeign的原因。

spring:
  servlet:
    multipart:
      max-file-size: 300MB
      max-request-size: 300MB

消费端:这里和服务端的一样,只是path不一样。

@PostMapping(path = "/filesystem/file/uploadFileByMultipartFile",consumes= {MediaType.MULTIPART_FORM_DATA_VALUE})
    String uploadFileByMultipartFile(@RequestParam("bucketName") String bucketName,@RequestParam("fileName") String fileName, @RequestPart("uploadFile") MultipartFile file);

大文件上传需要很长的时间,我这里暂时没有结合hystix.所以只配置了默认的全局的超时时间

yml中配置如下:

 

 最后测试:这里有一个比较坑的地方,自己构造的MultipartFile 中的第一个参数name 必须要和feign中@RequestPar注解中的name对应,不然会报错找不到映射,参数有错。

@RunWith(value = SpringRunner.class)
@SpringBootTest(classes = SystemApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TestApplication {


    @Autowired
    private FileSystemFeginClient fileSystemFeginClient;

   

    @Test
    public void testFileupload() throws Exception{
        File file = new File("D:\\download\\ces.rar");
//这里的第一个参数值 uploadFile是对应上面feign的文件注解中的@RequestPar中的name。一定要对应上
        MultipartFile multipartFile = new MockMultipartFile("uploadFile", file.getName(), "application/octet-stream;charset=utf-8", new FileInputStream(file));
        FileUploadMulRequestVO vo  = new FileUploadMulRequestVO();
        fileSystemFeginClient.uploadFileByMultipartFile("filedata","da3.rar", multipartFile);
    }
}

文件数组的还没有测试,有兴趣可以自己测试下

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐