当前位置:   article > 正文

RestTemple调用接口,上传文件form-data方式_resttemplate设置 form-data

resttemplate设置 form-data

前端调用后台服务上传文件,后端使用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("文件流关闭失败");
                }

            }
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/302919
推荐阅读
相关标签
  

闽ICP备14008679号