1.feign multipart 跨服务传递文件配置类(非全局配置)
public class FeignMultipartConfig {
@Bean
public Encoder multipartFormEncoder() {
return new SpringFormEncoder(new SpringEncoder(new ObjectFactory<HttpMessageConverters>() {
@Override
public HttpMessageConverters getObject() throws BeansException {
return new HttpMessageConverters(new RestTemplate().getMessageConverters());
}
}));
}
}
2.文件服务feign client
@FeignClient(name = "msfileupload", decode404 = true,configuration = FeignMultipartConfig.class)
public interface MsFileUploadFeignApi {
@RequestMapping(value = "/upload/single", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}
,consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
UploadResponse singleUpload(@RequestParam("bizType") String bizType, @RequestPart("file") MultipartFile file);
@RequestMapping(value = "/upload/multi", method = RequestMethod.POST,produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}
,consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
BaseRestResponse multiUpload(@RequestParam("bizType") String bizType, @RequestPart("files") MultipartFile[] files);
}
3.当前服务暴露给外部的feign client
@FeignClient(name = "demoservice", url = "${demoservice.feign.url:}" , fallback = FileUploadCommonApiFallBack.class)
public interface FileUploadCommonApi {
@RequestMapping(value = "/common/file/upload/single", method = RequestMethod.POST)
UploadResponse singleUpload(@RequestParam("bizType") String bizType, @RequestParam("file") MultipartFile file);
@RequestMapping(value = "/common/file/upload/multi", method = RequestMethod.POST)
BaseRestResponse multiUpload(@RequestParam("bizType") String bizType
, @RequestParam("files") MultipartFile[] files);
}
4.当前服务控制器代码片段:
@Slf4j
@RestController("fileUploadCommonControllerV1")
@Api(value = "文件通用处理", tags= "文件上传通用控制器")
public class FileUploadCommonController implements FileUploadCommonApi {
@Autowired
MsFileUploadFeignApi msFileUploadFeignApi;
@ApiOperation(value = "单个文件上传", notes = "单文件上传")
@Override
public UploadResponse singleUpload(@RequestParam("bizType") String bizType
, @RequestParam("file") MultipartFile file) {
log.info("FileUploadCommonController.singleUpload ...");
return msFileUploadFeignApi.singleUpload(bizType,file);
}
@ApiOperation(value = "多个文件上传", notes = "多个文件上传")
@Override
public BaseRestResponse multiUpload(@RequestParam("bizType") String bizType
, @RequestParam("files") MultipartFile[] files) {
log.info("FileUploadCommonController.multiUpload ...");
return msFileUploadFeignApi.multiUpload(bizType,files);
}
}