httpclient

Spring RestTemplate 上传文件

2018-12-08  本文已影响0人  turboDong

最近在做一个项目,用Spring boot开发,需要接收微信小程序传过来的图片,压缩后发送到影像系统中保存,涉及到上传文件,现列举出两种RestTemplate上传文件的方案。

1. restTemplate从服务器文件系统中选文件上传。

从文件系统上传文件时,需要把文件转换成FileSystemResource,然后放入HttpEntity中即可。代码如下:

public UploadImageResponseVO uploadImg(String fileLocal) throws IOException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.setConnection("Keep-Alive");
        headers.setCacheControl("no-cache");
        FileSystemResource resource = new FileSystemResource(new File(fileLocal));
        HttpEntity<FileSystemResource> httpEntity = new HttpEntity<>(resource);
        ResponseEntity<Resource> responseEntity = restTemplate.postForEntity(serverUrl, httpEntity, Resource.class);
        //对读到的内容映射成对应的实体类
        XmlMapper xmlMapper = new XmlMapper();
        UploadImageResponseVO uploadImageResponseVO = xmlMapper.readValue(responseEntity.getBody().getInputStream(), UploadImageResponseVO.class);
        logger.debug("responseEntity: {} ", uploadImageResponseVO);
        return uploadImageResponseVO;
    }

2. restTemplate转发接收的文件,直接上传图片。

用multipart形式上传文件时,需要用到MultiValueMap<String, Object>类,用它装载文件对象以及multipart的表单数据。
这里涉及到一个文件,从request中拿文件往MultiValueMap放时,不能直接request.getFile()给multiValueMap,这样在restTemplate上传文件时,messageConverter转化时会报错,需要把request.getFile("file").getResource()的数据给multiValueMap。代码如下:

public UploadResponseVO resendUpload(String url,StandardMultipartHttpServletRequest request) throws IOException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
        parts.add("file",request.getFile("file").getResource());
        Enumeration<String> enumeration= request.getParameterNames();
        while(enumeration.hasMoreElements()){
            String key = enumeration.nextElement();
            parts.add(key,request.getParameter(key));
        }
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(parts, headers);
        ResponseEntity<UploadResponseVO> responseEntity = restTemplate.postForEntity(url,httpEntity,UploadResponseVO.class);
        return responseEntity.getBody();
    }
上一篇下一篇

猜你喜欢

热点阅读