RestTemplate转发MultipartFile

需求背景:

公司有一个上传文件的内部接口,但是由于网络路线没有打通,导致外部不能直接访问这个接口,现在需要新增一个外部能访问的接口,然后通过这个外部接口代理到内部的文件上传接口。


功能实现

关于RestTemplate发送数据的案例有很多,但是这次需要使用RestTemplate转发MultipartFile文件,网上很多都说需要将要转发的文件保存到本地作为零时文件,然后通过**new FileSystemResource(localFile)**后来发送文件。但是我觉得应该有更好的方法,通过查看MultipartFile的源码,其中getResource()方法有这样一段话,才解决了我的疑惑。

	/**
	 * Return a Resource representation of this MultipartFile. This can be used
	 * as input to the {@code RestTemplate} or the {@code WebClient} to expose
	 * content length and the filename along with the InputStream.
	 * @return this MultipartFile adapted to the Resource contract
	 * @since 5.1
	 */
	default Resource getResource() {
		return new MultipartFileResource(this);
	}

MultipartFile官方提供了getResource()方法返回一个MultipartFile的资源形式,并且可以将返回都Resouce作为RestTemplate或者WebClient的输入。那么RestTemplate转发MultipartFile的实现就可以这样实现:

    @RequestMapping(method = RequestMethod.POST, value = "/upload/logFiles", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public String receiveFile(@RequestParam String vin,
                              @RequestParam(required = false, value = "Command_session_ID") Object cmdSessionIdStr,
                              @RequestParam String progress, @RequestParam String sig, @RequestParam String iv,
                              @RequestHeader("Authorization") String token,
                              HttpServletRequest request) {
        //获取上传文件列表                      
        MultiValueMap<String, MultipartFile> multiFileMap = ((MultipartHttpServletRequest) request).getMultiFileMap();
        //获取文件列表第的第一个文件key
        String first = (String) multiFileMap.keySet().iterator().next();
        //获取文件列表中第一个文件
        MultipartFile file = (MultipartFile) multiFileMap.getFirst(first);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", token);
        //设置请求类型
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        LinkedMultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("vin", vin);
        params.add("Command_session_ID", cmdSessionIdStr);
        params.add("progress", progress);
        params.add("sig", sig);
        params.add("iv", iv);
        //将获取的MultipartFile文件放入HttpEntity中
        params.add("file", file.getResource());
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(params, headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(logUpLoadUrl, HttpMethod.POST, requestEntity, String.class);
        return responseEntity.getBody();
    }
  • 8
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值