解决feign微服务间的文件上传报错问题

网友投稿 1238 2023-01-02

解决feign微服务间的文件上传报错问题

解决feign微服务间的文件上传报错问题

A微服务调用B服务的上传文件接口报错:

the request was rejected because no multipart boundary was found

spring cloud版本 H

org.springframework.cloud

spring-cloud-dependencies

Hoxton.SR8

pom

import

如果你是使用feign相信你已经引入openfeign的依赖了;

org.springframework.cloud

spring-cloud-starter-openfeign

服务提供者接口:

//服务提供者上传文件接口

@PostMAPPing(value = " /file/upload")

public ResultModel 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 fileUpload(@RequestParam("access_token") String accessToken, @RequestIDrCjtPart("file") MultipartFile file);

}

必须加

consumes = MediaType.MULTIPART_FORM_DATA_VALUE

MultipartFile file 前面的注解必须是@RequestPart

消费者controller类:

//消费者上传文件接口

@PostMapping(value = "/fileUpload")

public ResultModel fileUpload(@RequestParam("access_token") String accessToken, @RequestPart("file") MultipartFile file) {

return fileInfoFeignService.http://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 parts = request.getParts();

logger.info(JSONObject.toJSONString(parts, true));

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:盐城企业app开发订制(盐城APP开发公司)
下一篇:vue 小程序组件通信(vue 子组件之间的通信)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~