欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spirng restTemplate发送 MultipartFile 文件调用接口

程序员文章站 2022-03-04 19:15:04
...
public JSONObject upload(MultipartFile file){
    try {
        log.info("上传图片证明材料");
        HashMap<String, Object> map = new HashMap<>();
        map.put("file",file);
        ByteArrayResource fileAsResource = new ByteArrayResource(file.getBytes()) {
            @Override
            public String getFilename() {
                return file.getOriginalFilename();
            }

            @Override
            public long contentLength() {
                return file.getSize();
            }
        };
        MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
        multipartRequest.add("file", fileAsResource);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity (multipartRequest,headers);
        ResponseEntity<JSONObject> entity = restTemplate.postForEntity("http://xxxxx/contract/upload", requestEntity, JSONObject.class);
        JSONObject body = entity.getBody();
        return body;
    } catch (Exception e) {
        e.printStackTrace();
        String s = JSONObject.toJSONString(CommonResult.failed("保存失败"));
        return JSON.parseObject(s);
    }
}