Java 将内容使用zip传给前端

43 阅读1分钟

Java 将内容使用zip传给前端

java使用zip,Java将文本用zip传给前端

public ResponseEntity<byte[]> downloadByZip(VmsArgumentDto dto) {
    // 需要下载的数据
    List<GeneratorVo> generatorVoList = generator(dto);
​
    // 1. 创建临时ZIP文件
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    try (ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream)) {
        // 2. 遍历并创建
        generatorVoList.forEach(generatorVo -> {
            // zip中的路径
            String path = generatorVo.getPath().replace(".vm", "");
​
            // zip中的文件
            String code = generatorVo.getCode();
​
            ZipEntry zipEntry = new ZipEntry(path);
            try {
                // 如果有 / 会转成文件夹
                zipOutputStream.putNextEntry(zipEntry);
​
                // 写入文件
                zipOutputStream.write(code.getBytes(StandardCharsets.UTF_8));
                zipOutputStream.closeEntry();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
​
    // 2.1 文件不重名
    long currentTimeMillis = System.currentTimeMillis();
    String digestHex = MD5.create().digestHex(currentTimeMillis + "");
​
    // 3. 准备响应
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Disposition", "attachment; filename=" + "vms-" + digestHex + ".zip");
    headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
    headers.add("Pragma", "no-cache");
    headers.add("Expires", "0");
​
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    return new ResponseEntity<>(byteArrayInputStream.readAllBytes(), headers, HttpStatus.OK);
}

其中 putNextEntry可以将/当成路径。