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