栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot中使用RestTemplate发送文件流,附(读取zip压缩包中的文件方法)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot中使用RestTemplate发送文件流,附(读取zip压缩包中的文件方法)

接收方与发送方代码

@RestController
@RequestMapping("/optimistic")
public class OptimisticController {
    @Resource
    private RestTemplate restTemplate;

    //接收方
    @PostMapping("receive")
    public String receive(@RequestParam(value = "file",required = false) MultipartFile uploadFile) {
        String originalFilename = uploadFile.getOriginalFilename();
          return originalFilename;
    }
    //发送方
    @PostMapping("send")
    public String send(@RequestParam(value = "file",required = false) MultipartFile uploadFile) throws IOException {
       //设置content-type为 multipart/form-data
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        //获取流文件
        InputStream inputStream = uploadFile.getInputStream();
        InputStreamResource fileResource = new InputStreamResource(inputStream) {
            //重写设置文件大小与名称
            @Override
            public long contentLength() {
                return uploadFile.getSize();
            }

            @Override
            public String getFilename() {
                return uploadFile.getOriginalFilename();
            }
        };
        MultiValueMap param = new LinkedMultiValueMap<>();
        param.add("file",fileResource);
        HttpEntity> requestEntity = new HttpEntity<>(param, headers);
        String body = restTemplate.exchange("http://127.0.0.1:8088/optimistic/receive", HttpMethod.POST, requestEntity, String.class).getBody();
        return body;
    }
}

请求发送方接口成功返回

 读取zip压缩包中的文件方法

创建main函数测试

    public static void main(String[] args) throws IOException {
        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("D://jobhandler/zip/test.zip"));
        ZipInputStream zis  = new ZipInputStream(bufferedInputStream);
        ZipEntry zipEntry;
        BufferedReader br = new BufferedReader(
                new InputStreamReader(zis));
        while ((zipEntry = zis.getNextEntry()) != null) {
            // 解压压缩文件的其中具体的一个zipEntry对象
            String name = zipEntry.getName();
            try {
                StringBuffer sb = new StringBuffer();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                    sb.append("rn");
                }

                System.out.println(sb);

            } catch (Exception e) {
                e.printStackTrace();
            }
            zis.closeEntry();
        }
        zis.close();
        br.close();

    }

成功读取zip中的json文件

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/926627.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号