这里写自定义目录标题
- B模块上传文件调用了A模块的文件保存实现
- 1.1 业务场景
- 2.1 排查过程
- 3.1 解决办法
- 4.1 知识扩展
-
- 完整代码
- 1 引入OpenFeign依赖
- A模块(提供方)
-
- B 模块(调用方)
- service 层
- 有问题可以私信我,或者评论, 看到会回复
B模块上传文件调用了A模块的文件保存实现
1.1 业务场景
首先在A模块中写好了上传文件并保存文件的接口与实现,
其次 B模块在开发中,需要调用A模块的接口
A模块接口 使用form-data传输file文件
B模块在使用OpenFeign调用A接口时, 出现异常:
feign.FeignException: status 400 reading xxx
2.1 排查过程
A 模块接口正常
B 模块使用form-data接受正常
B 模块调用A模块接口,传参时异常, 因为调用OpenFeign时没有使用form-data
3.1 解决办法
方法: B 模块 在使用OpenFeign 调用A模块接口时, 需要 如下改动
- 在@PostMapping() 指定consumes (详细含义,看4.1章节)
- file 使用@RequestPart 注解
@ApiOperation(value = "添加拓扑图CAD设计图纸")
@PostMapping(path = "/design/file/target/{id}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
DesignFile addDesignFile(@PathVariable("id") Integer targetId,
@RequestParam(value = "targetType") String targetType,
@RequestPart("file") MultipartFile file);
该代码中有需要注意:
必须是Post类型的请求。
文件形参必须用@RequestPara MultipartFile file来修饰,其中 @RequestParat和MultipartFile必不可少。
4.1 知识扩展
4.1.1 @PostMapping 参数含义
@PostMapping是专门描述post请求的注解
@PostMapping等同于@RequestMapping(method = RequestMethod.POST)
参数 | 含义 |
---|
path | 请求路径 |
consumes | 请求提交的内容格式 |
method | 请求类型 |
4.1.2 接口参数描述
参数 | 含义 |
---|
@PathVariable(“参数名”) 类型 变量名 | 参数在url中写, URL占位中的参数 |
@RequestParam(value=“参数名”) 类型 变量名 | 参数在body中写,是URL中?后面的参数 |
@RequestPart(“参数名”) MultipartFile 变量名 | 特指文件传递时使用,是修改文件的参数 |
完整代码
1 引入OpenFeign依赖
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form</artifactId>
<version>xxx</version>
</dependency>
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form-spring</artifactId>
<version>xxx</version>
</dependency>
A模块(提供方)
controller层
@RestController
public class DesignFileController {
@SneakyThrows
@ApiOperation(value = "添加拓扑图CAD设计图纸")
@PostMapping("/design/file/target/{id}")
public DesignFile addDesignFile(@PathVariable("id") Integer targetId,
@RequestParam(value = "targetType") String targetType,
@RequestParam("file") MultipartFile file) {
val fileName = file.getOriginalFilename();
return this.designFileService.addDesignFile(targetId, fileName, description, targetType);
}
}
B 模块(调用方)
service 层
@FeignClient(
name = "multipart-support-service",
url = "http://localhost:8080",
configuration = Client.ClientConfiguration.class
)
public interface GraphService {
@ApiOperation(value = "添加拓扑图CAD设计图纸")
@PostMapping(path = "/design/file/target/{id}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
DesignFile addDesignFile(@PathVariable("id") Integer targetId,
@RequestParam(value = "targetType") String targetType,
@RequestParam(value = "description", required = false) String description,
@RequestPart("file") MultipartFile file);
}
有问题可以私信我,或者评论, 看到会回复
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)