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

2023年2月16日08:55:34

接收方与发送方代码

@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<String, Object> param = new LinkedMultiValueMap<>();
        param.add("file",fileResource);
        HttpEntity<MultiValueMap<String, Object>> 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("\r\n");
                }

                System.out.println(sb);

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

    }

成功读取zip中的json文件

  • 作者:小王同鞋
  • 原文链接:https://blog.csdn.net/m0_60215634/article/details/124932117
    更新时间:2023年2月16日08:55:34 ,共 1846 字。