赞
踩
前端调用后台服务上传文件,后端使用restTemple调用接口把文件传到其他服务上去
@RequestMapping("/test") public void upload(MultipartFile file) { String originalFilename = file.getOriginalFilename(); // 生成临时文件 String tempPath = System.getProperty("java.io.tmpdir"); File tempFile = new File(tempPath + originalFilename); InputStream inputStream = null; try { if (!tempFile.exists()) { inputStream = file.getInputStream(); Files.copy(inputStream, tempFile.toPath(), new CopyOption[0]); } FileSystemResource resource = new FileSystemResource(tempFile); MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>(); multiValueMap.add("file", resource); HttpHeaders headers = new HttpHeaders(); // 设置请求格式form-date格式 headers.setContentType(MediaType.MULTIPART_FORM_DATA); HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(multiValueMap, headers); // 上传文件地址 String url = "http://"; //ParameterizedTypeReference 直接返回包装好的对象 ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, new ParameterizedTypeReference<T>() { }); // 调用接口返回结果 String body = responseEntity.getBody(); Files.delete(tempFile.toPath()); } catch (IOException e) { log.error("文件流处理失败"); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { log.error("文件流关闭失败"); } } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。