restTemplate发送post请求提交formdata


public ResponseEntity download(@RequestParam MultipartFile file, @RequestParam Integer type) {
    File fileTemp = null;
  String url = http://127.0.0.1/api
    try {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.set("Authorization","Bearer " + getToken());
        fileTemp = File.createTempFile("cw-", file.getOriginalFilename());
        file.transferTo(fileTemp);

        MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>();
        multiValueMap.add("type", type);
        multiValueMap.add("multipartFile", new FileSystemResource(fileTemp));

        HttpEntity<MultiValueMap<String, Object>> params = new HttpEntity<>(multiValueMap, headers);
        JSONObject response = restTemplate.postForObject(url, params, JSONObject.class);

        Integer code = response.getInteger("code");
        String msg = response.getString("msg");
        JSONObject data = null;
        if (code == 200) {
            data = response.getJSONObject("data");
        }
        Map map = new HashMap();
        map.put("data",data);
        map.put("code",code);
        map.put("msg",msg);
        return new ResponseEntity<>(map, HttpStatus.OK);
    } catch (Exception e){
        e.printStackTrace();
    } finally {
        if(fileTemp != null && fileTemp.exists()) {
            fileTemp.delete();
        }
    }
    Map map = new HashMap();
    map.put("code",500);
    map.put("token",null);
    map.put("msg","导入失败");
    return new ResponseEntity<>(map, HttpStatus.INTERNAL_SERVER_ERROR);
}

  核心代码已标红

posted @ 2023-05-12 16:27  曹伟666  阅读(949)  评论(0编辑  收藏  举报