A微服务调用B服务的上传文件接口报错: the request was rejected because no multipart boundary was found spring cloud版本 H dependency groupIdorg.springframework.cloud/groupId artifactIdspring-cloud-dependencies/artifactId v
A微服务调用B服务的上传文件接口报错:
the request was rejected because no multipart boundary was found
spring cloud版本 H
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Hoxton.SR8</version> <type>pom</type> <scope>import</scope> </dependency>
如果你是使用feign相信你已经引入openfeign的依赖了;
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
服务提供者接口:
//服务提供者上传文件接口 @PostMapping(value = " /file/upload") public ResultModel<FileInfo> fileUpload(@RequestParam("access_token") String accessToken, @RequestParam("file") MultipartFile file) { //返回保存文件信息的实体类 FileInfo fileInfo = fileInfoService.uploadFile(file); return ResultModel.ok(fileInfo); }
消费者接口:
@Component @FeignClient(value = "file-server") public interface FileInfoFeignService { @PostMapping(value = "/file/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public ResultModel<FileInfo> fileUpload(@RequestParam("access_token") String accessToken, @RequestPart("file") MultipartFile file); }
必须加
consumes = MediaType.MULTIPART_FORM_DATA_VALUE
MultipartFile file 前面的注解必须是@RequestPart
消费者controller类:
//消费者上传文件接口 @PostMapping(value = "/fileUpload") public ResultModel<FileInfo> fileUpload(@RequestParam("access_token") String accessToken, @RequestPart("file") MultipartFile file) { return fileInfoFeignService.fileUpload(accessToken, file); }
这样就完成了!
自己调试了很多遍,感觉其他的博客写的乱七八糟的。
feign上传文件踩坑及解决
通过 feign 调用文件服务提供者接口时,需传输 文件file ,服务调用者有时会报错误:
feign.FeignException$BadRequest: status 400 reading
服务提供者会报 Required request part 'file' is not present 错误。
这是因为服务调用者MultipartFile的value跟服务提供者@RequestPart中的value值不一样导致的。
在服务调用者MultipartFile的value要跟服务提供者的@RequestPart中的value值一样。不然它会抛出400异常!!!
示例
服务调用者
@PostMapping("/xxx/file") public xx uploadOrderFilesToOSS(@ApiParam("附件") @RequestParam("file") MultipartFile[] file) { return xxxService.uploadOrderFilesToOSS(file); }
Feign
@PostMapping(value = "/file", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) xxx uploadSigleFile(@RequestParam("path") String path, @RequestPart("file") MultipartFile file);
服务提供者
@PostMapping(value = "/file", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public xxx uploadSigleFile(@RequestParam("path") String path, @RequestPart("file") MultipartFile file) { return fileService.uploadFileToOSS(path, file); }
可以通过以下代码查看请求参数
Collection<Part> parts = request.getParts(); logger.info(JSONObject.toJSONString(parts, true));
以上为个人经验,希望能给大家一个参考,也希望大家多多支持自由互联。