java中批量导出文件并压缩到zip文件中

本文介绍了一个使用Java和SpringMVC开发的应用,处理文件批量导出和压缩为ZIP,包括数据库查询、HTTP响应头设置和文件流操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近开发遇到个问题 批量导出并压缩到zip文件中,代码和思路如下 不做赘余的解释…

@PostMapping("/downLoads")
	public void downLoadCategoryFiles(@RequestBody List<String> fileUids, HttpServletResponse response) throws Exception {
		// 取得文件信息
		List<xxx> file = this.service.listByIds(fileUids);
		if (file.size() == 0) {
			throw new CheckedException("文件信息丢失");
		}
		
		this.service.getCategoryFiles(fileUids, response);
	}

service层代码

void getCategoryFiles(List<String> fileUid, HttpServletResponse response) throws Exception;

实现层业务代码如下:

@Override
	public void getCategoryFiles(List<String> fileUids, HttpServletResponse response) throws Exception {
		List<实体类> files = this.listByIds(fileUids);
		if (files.size() == 0) {
			throw new RuntimeException("文件已被删除。");
		}
		
		//将路径放到一个list中去
		List<String> fullPaths = files.stream().map(实体类::getFullPath).collect(Collectors.toList());
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String year = sdf.format(new Date());//获取当前年月日
		
		//设置文件/名称
		response.addHeader("Content-Type", "application/zip");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + year + ".zip\"");

        //逻辑处理
        try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream()); ) {
            for (String fileName : fullPaths) { //循环往zip中放入文件
                File file = new File(fileName);
                FileInputStream fileIn = new FileInputStream(file);
                ZipEntry zipEntry = new ZipEntry(file.getName());
                zipOut.putNextEntry(zipEntry);
                byte[] buffer = new byte[1024];
                int len;
                while ((len = fileIn.read(buffer)) > 0) {
                    zipOut.write(buffer, 0, len);
                }
                fileIn.close();
                zipOut.closeEntry();
            }
            zipOut.finish();
        } catch (Exception e) {
        	throw new RuntimeException("文件批量下载有误.", e);
        }
	} 

最后一层 代码中所提到的"实体类",自我填充即可.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值