Spring RestTemplate 上传文件

最近在做一个项目,用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();
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,737评论 19 139
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong阅读 22,984评论 1 92
  • 当Django在处理文件上传的时候,文件数据被保存request.FILES 。这篇文档阐述文件如何上传到内存和硬...
    低吟浅唱1990阅读 1,722评论 0 3
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,291评论 6 342
  • 今天早上和eva上了一节亲子课,讲了站点。下午两点也上了一节课,晚上七点和tiger也带了一节课。 亲子班认识了帅...
    桥上桥树阅读 196评论 0 0

友情链接更多精彩内容