Java实现Web页面下载zip、tar包-Demo

实现思路:后台程序读取文件,把数据写给浏览器;即输入流读文件,写到浏览器的输出流中

Demo代码:

@RestController
@RequestMapping("/test")
public class TestController {

    @GetMapping("/zip")
    public void zip(HttpServletResponse response) {
        response.reset();
        response.setContentType("application/multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;filename=test.zip");
        try (ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()))) {
            String content_test_1 = "test_zip_1";
            String content_test_2 = "test_zip_2";
            zos.putNextEntry(new ZipEntry(content_test_1));
            zos.write(content_test_1.getBytes(StandardCharsets.UTF_8));
            zos.putNextEntry(new ZipEntry(content_test_2));
            zos.write(content_test_1.getBytes(StandardCharsets.UTF_8));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/tar")
    public void tar(HttpServletResponse response) {
        response.reset();
        response.setContentType("application/multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;filename=test.tar");
        try (TarArchiveOutputStream tarOps = new TarArchiveOutputStream(new BufferedOutputStream(response.getOutputStream()))){
            String content_test_1 = "test_tar_1";
            String content_test_2 = "test_tar_2";


            TarArchiveEntry entry_1 = new TarArchiveEntry("test_tar_1");
            entry_1.setSize(content_test_1.length());
            tarOps.putArchiveEntry(entry_1);
            tarOps.write(content_test_1.getBytes(StandardCharsets.UTF_8));
            tarOps.closeArchiveEntry(); // 需要关闭

            TarArchiveEntry entry_2 = new TarArchiveEntry("test_tar_2");
            entry_2.setSize(content_test_2.length());
            tarOps.putArchiveEntry(entry_2);
            tarOps.write(content_test_2.getBytes(StandardCharsets.UTF_8));
            tarOps.closeArchiveEntry();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值