环境介绍
客户端环境
依赖包 | 版本 |
---|---|
gradle | 6.7.1 |
springboot | 2.3.0.RELEASE |
springCloud | Hoxton.SR6 |
服务端环境
依赖包 | 版本 |
---|---|
gradle | 5.4.1 |
springboot | 2.3.0.RELEASE |
springCloud | Hoxton.SR6 |
代码
客户端
feign代码
@FeignClient(name = "xx", primary = false, configuration = CreateFeignClient.MultipartSupportConfig.class)
public interface CreateFeignClient {
@Configuration
class MultipartSupportConfig {
@Bean
public AbstractFormWriter jsonFormWriter() {
return new JsonFormWriter();
}
}
@PostMapping(value = "/xx", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
ResultVo create(@RequestPart("file") MultipartFile file, @RequestPart("createVo") CreateVo createVo);
}
构建MultipartFile对象
public MultipartFile initFile(String path){
File file = new File(path);
try {
FileInputStream fileInputStream = new FileInputStream(file);
return new MockMultipartFile("file", file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
} catch (IOException e) {
log.error("文件转换失败->", e);
throw new IllegalArgumentException("文件转换失败");
}
}
注意:
构建MultipartFile对象中new MockMultipartFile(“file”, file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);要与feign接口ResultVo create(@RequestPart(“file”) MultipartFile file, @RequestPart(“createVo”) CreateVo createVo);中标红地方相同,否则服务端会报错 Required MultipartFile parameter ‘file’ is not present
服务端
Controller代码
@PostMapping(value = "/xx")
public ResultVo create(@RequestPart("file") MultipartFile file, @RequestPart("createVo") CreateVo createVo){
ResultVo vo = new ResultVo();
vo.setOriginalFilename(file.getOriginalFilename());
vo.setUserNames(contractVo.getUsers().stream().map(s -> s.getUserName()).collect(Collectors.toList()));
return vo;
}
🤵♂️ 个人博客: www.tingyinhu.com
🎨 微信公众号:java编程秀✏️记录基础知识,做大家的备忘录。
🚀分享前沿技术,做大家的加油站。📝 如果文章对你有帮助的话,欢迎 「分享⏩在看👀点赞👍收藏📂」,不胜感激!