springboot微服务间上传文件


springboot微服务之间通常使用feign进行接口调用,那么在此基础上文件上传如何操作呢?

最近项目中碰到了这种需求,此处分享一下使用心得,希望对大家有帮助!!!

一、我这里使用的相关包如下,其它的大家视情况而定

         <dependency>
            <groupId>io.github.openfeign.form</groupId>
            <artifactId>feign-form-spring</artifactId>
            <version>3.3.0</version>
        </dependency>                        

  二、配置文件相关配置如下:

spring:
  servlet:
    multipart:
      enabled: true # 启用上传处理,默认是true
      file-size-threshold: 1MB # 当上传文件达到1MB的时候进行磁盘写入
      max-request-size: 100MB # 设置最大的请求文件的大小
      max-file-size: 2MB # 设置单个文件的最大长度

  三、启动加载相关配置

@Configuration
public class FeignMultipartSupportConfig {

    @Autowired
    private ObjectFactory<HttpMessageConverters> messageConverters;

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

  四、调用方Feign接口

@FeignClient(name = "ms-merchant-basis-server")
public interface AttachmentFegin {
    @PostMapping(value = "/api/upload/image", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ApiOperation(value = "上传图片,文件不能为空,大小不能超过10M")
    PicVo uploadImage(@RequestPart("file") MultipartFile file);
}

    注:

      consumes:必须使用 MediaType.MULTIPART_FORM_DATA_VALUE
      produces:接口多参数时增加此配置 MediaType.APPLICATION_JSON_UTF8_VALUE
      @RequestPart:服务调用方接口文件类型使用此注解 

  五、被调用方Controller接口

    @RequestMapping(value = "/api/upload/image", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "上传图片,文件不能为空,大小不能超过10M")
    public void uploadImage(@RequestParam("file") MultipartFile file)  {}

            注:

      @RequestParam :此注解包含@RequestPart,但是@RequestPart不包含@RequestParam

最后给大家来张宅男图片缓解一下眼睛

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM