SpringCloud Feign文件上传

需求就是服务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") 括号中的值。


如有不足之处,欢迎指正。

参考:https://segmentfault.com/a/1190000016234692

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值