赞
踩
请求端:
1. 封装参数
- MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>();
- List<Resource> tmpResource = new ArrayList<>();
- Arrays.stream(multipartfiles).forEach(multipartFile -> {
- tmpResource.add(multipartFile.getResource());
- });
- multiValueMap.addAll("file", tmpResource);
- multiValueMap.add("req", fileUploadReq);
2.远程调用
- Resp result = BaseUtil.postForObject2(restTemplate, RestApi.UPLOAD_FILE, multiValueMap, Resp.class, MediaType.MULTIPART_FORM_DATA);
- if (null != result && result.getCode().equals(CODE.success.getCode())) {
- log.info("RestApi.UPLOAD_FILE=====" + result.getCode());
- }
远程调用中封装的postForObject2方法
- public static <T> T postForObject2(RestTemplate restTemplate, String url, Object obj, Class<T> respType, MediaType mediaType) {
- log.info("开始调用远程服务....");
- if (StringUtil.isNull(url)) {
- log.error("请求url不能为空");
- return null;
- }
- if (null == respType) {
- log.error("响应类型不能为空");
- return null;
- }
- log.info("请求地址:" + url);
- log.info("请求参数:" + (obj == null ? "" : obj.toString()));
-
- /**设置请求头*/
- HttpHeaders headers = new HttpHeaders();
- if (mediaType == null) {
- headers.setContentType(MediaType.APPLICATION_JSON);
- } else {
- headers.setContentType(mediaType);
- }
-
- /**设置请求体*/
- HttpEntity<Object> entity = new HttpEntity<>(obj, headers);
-
- /**请求*/
- T resp;
- try {
- resp = restTemplate.postForObject(url, entity, respType);
- log.info("响应结果:" + (resp == null ? null : resp.toString()));
- } catch (Exception e) {
- log.error("远程调用异常:" + e.toString());
- return null;
- }
- log.info("调用远程服务完成====");
- return resp;
- }
服务端:
- /**
- * 服务之间调用上传文件入口
- * @param file
- * @param req
- * @return
- * @throws Exception
- */
- @RequestMapping("uploadFileCommonForService")
- public FileUploadReq uploadFileCommonForService(@Valid List<MultipartFile> file, @RequestPart FileUploadReq req) throws Exception {
- return iFileUploadService.uploadFileCommon(file, req);
- }
另外一种方式 feigin方式传递文件:https://blog.csdn.net/buyaopingbixiazai/article/details/115537084
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。