我在网上查了很多关于 Spring Cloud 文件上传的相关资料也花费了不少时间,根据他们提供的方案修改也没有得到解决,终于在朋友的帮忙下,终于解决了我的问题,也与大家分享了下,如下:
一、项目结构
首先介绍一下项目结构,我们开发的项目结构比较简单
xxx-api工程:这个工程主要是对外提供接口.
xxx-core工程:这个工程承载核心业务处理.
二、上代码
对于开发者来说,看代码比较实在,如下:
xxx-api工程下的文件上传相关代码:
1、Controller类(注意红色的标记)
@ApiOperation("文件上传接口")
@PostMapping(value = "/fileUpload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public RespMsg<Map<String, String>> fileUpload(@RequestPart(value = "file",required = false) MultipartFile file){
try {
Map<String, String> map = uploadFeginClient.fileUpload(file,"certificate");
return RespMsg.success(map);
} catch (Exception e) {
e.printStackTrace();
return RespMsg.error();
}
}
2、FeginClient类(注意红色的标记)
/**
* @author 潘浩
* @Title: UserAccountClient.java
* @Description: 文件上传
*/
@FeignClient(name = "upload", url = "${mallcore.http.url}",
configuration = UploadFeginClient.ClientConfiguration.class)
public interface UploadFeginClient {
/**
* 文件上传
* @param file
* @return
* @throws Exception
*/
@PostMapping(value = "/mallapi/upload/fileUpload",
produces = {MediaType.APPLICATION_JSON_UTF8_VALUE},
consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Map<String, String> fileUpload(@RequestPart(value = "file") MultipartFile file,
@RequestParam(value = "type") String type) throws Exception;
//文件配置转换 (内部类)
class ClientConfiguration{
@Autowired
private ObjectFactory<HttpMessageConverters> messageConverters;
/**
* @Description // 此处注入的是: ObjectFactory<HttpMessageConverters>
* @Date 23:04 2020/4/9
* @Param []
* @return feign.form.spring.SpringFormEncoder
**/
@Bean
public Encoder feignEncoder() {
return new SpringFormEncoder(new SpringEncoder(messageConverters));
}
}
}
二、xxx-core工程下的相关代码,如下:
以下是 FeignClient类调用Core工程Controller类,如下:
1、Controller类
@ApiOperation("文件上传接口.")
@PostMapping(value = "/fileUpload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Map<String, String> fileUpload(@RequestPart(value = "file") MultipartFile file,
@RequestParam(value = "type") String type) throws Exception {
// 这里将文件上传到服务器,这个比较好解决的.
return uploadService.fileUpload(file, type);
}
本文主要介绍了在Spring Cloud Feign中遇到文件上传时提示'no multipart boundary was found'的问题,通过分析项目结构和关键代码,分享了解决方案。在FeignClient配置中,使用SpringFormEncoder并注入HttpMessageConverters,从而正确处理multipart/form-data请求。
3129





