通过我们使用spring系列的框架上传文件,都会利用MultipartFile文件流进行文件的上传。但是我在最近的项目中遇到一个问题,我们的项目是基于springboot框架的springcloud微服务搭建的,后端服务技术希望用feign来做对外统一开放的接口服务。在服务之间的调用时,发现MultipartFile文件流上传文件会报错,在网上找了很久,找到了解决方案:
一、编写配置类
编写一个配置类,也就是把multipart/form-data格式的文件流编码为spring框架能够解析的格式
/**
* spring能够解析multipart/form-data格式的文件流 配置类
*
* @author wu
* @version 1.0
* @date 2020/12/9/009
*/@ConfigurationpublicclassMultipartSupportConfig{@Autowiredprivate ObjectFactory<HttpMessageConverters> messageConverters;@Beanpublic EncoderfeignFormEncoder(){returnnewSpringFormEncoder(newSpringEncoder(messageConverters));}}
在服务调用方加注解类
import org.springframework.cloud.openfeign.FeignClient;import org.springframework.http.MediaType;import org.springframework.web.bind.annotation.*;import org.springframework.web.multipart.MultipartFile;/**
* @author wu
* @version 1.0
* @date 2020/12/1/001
*/@FeignClient(value="xxxxx", configuration= MultipartSupportConfig.class)publicinterfaceFileService{/**
* 文件上传
*
* @param file
* @param fileType
* @return
*/@PostMapping(value="/upload",consumes= MediaType.MULTIPART_FORM_DATA_VALUE)
ResponseEntityupload(@RequestPart(value="file") MultipartFile file,@RequestParam(value="fileType") String fileType);
注意:文件流要用RequestPart注解传参,其余参数用RequestParam注解传参