需求就是服务B调用服务A的文件上传接口。
服务A
- Controller:
@PostMapping("/remoteUpload")
public R remoteUpload(@RequestPart("file") MultipartFile file,
@RequestParam("xxxId") String dataId,
@RequestParam("xxxType") String dataType) {
// xxx
return R.ok();
}
- FeignClient:
@FeignClient(contextId = "remoteXXXXService", value = "XXXXService")
public interface RemoteXXXService {
@PostMapping(value = "/file/remoteUpload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
R remoteUpload(@RequestPart("file") MultipartFile file,
@RequestParam("xxxId") String xxxId,
@RequestParam("xxxType") String xxxType;
}
注意:
1. @PostMapping的 /file/ , 是服务A中Controller的映射地址:@RequestMapping("/file")
2. 指定 consumes ,防止不必要的报错
服务B
- 调用:
@Service
@AllArgsConstructor
public class XXXServiceImpl implements XXXService {
private final RemoteXXXService remoteXXXService;
private void xxxx(){
MultipartFile multipartFile = xxxx;
remoteXXXService.remoteUpload(multipartFile, "xxxId", "xxxType");
}
}
关于创建MultipartFile对象
我在开发中的需求,是把excel转成MultipartFile对象,进行文件上传,所以,下面列出的是Workbook转换MultipartFile的代码:
@SneakyThrows
public static MultipartFile workbookToMultipartFile(Workbook workbook, String fileName){
DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file",
MediaType.ALL_VALUE, true, fileName);
OutputStream os = fileItem.getOutputStream();
workbook.write(os);
return new CommonsMultipartFile(fileItem);
}
1.参数fileName我是连文件后缀名也写上。
2.createItem()方法第一个参数对应@RequestPart("file") 括号中的值。
如有不足之处,欢迎指正。

372

被折叠的 条评论
为什么被折叠?



