Java 将多个文件打包为zip压缩包并提供给前端下载

一、文件打包为zip

public void zip(List<File> fileList,String zipFileName) {
		FileInputStream fileInputStream = null;
		FileOutputStream fileOutputStream = null;
		ZipOutputStream zipOutputStream = null;
		BufferedInputStream bufferInputStream = null;
		try {
			// zipFileName为压缩文件的名称(xx.zip),首先在某个目录下(C:/temp/路径可以根据自己的需求进行修改)创建一个.zip结尾的文件
			fileOutputStream = new FileOutputStream(new File("C:/temp/" + zipFileName));
			zipOutputStream = new ZipOutputStream(new BufferedOutputStream(fileOutputStream));
			// 创建读写缓冲区
			byte[] bufs = new byte[1024 * 10];

			for (File file : fileList) {
				// 创建ZIP实体,并添加进压缩包
				ZipEntry zipEntry = new ZipEntry(file.getName());
				zipOutputStream.putNextEntry(zipEntry);

				// 读取待压缩的文件并写进压缩包里
				fileInputStream = new FileInputStream(file);
				bufferInputStream = new BufferedInputStream(fileInputStream, 1024 * 10);
				int read = 0;
				while ((read = bufferInputStream.read(bufs, 0, 1024 * 10)) != -1) {
					zipOutputStream.write(bufs, 0, read);
				}
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (bufferInputStream != null) {
					bufferInputStream.close();
				}
				if (zipOutputStream != null) {
					zipOutputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

二、下载zip包

	public void downloadZip(HttpServletResponse response, String zipFileName) {
		// zipName为上一步文件打包zip时传入的zipName
		File zipFile = new File("C:/temp/" + zipFileName);
		response.setContentType("APPLICATION/OCTET-STREAM");
		response.setHeader("Content-Disposition", "attachment; filename=" + zipFileName);

		FileInputStream fileInputStream = null;
		OutputStream outputStream = null;
		try {
			outputStream = response.getOutputStream();
			fileInputStream = new FileInputStream(zipFile);
			byte[] bufs = new byte[1024 * 10];
			int read = 0;
			while ((read = fileInputStream.read(bufs, 0, 1024 * 10)) != -1) {
				outputStream.write(bufs, 0, read);
			}
			fileInputStream.close();
			outputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				// 删除压缩包
				File file = new File("C:/temp/" + zipFileName);
				file.delete();
                
				if (fileInputStream != null) {
					fileInputStream.close();
				}
				if (outputStream != null) {
					outputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

三、下载接口

	@GetMapping("/downloadZip")
	@ApiOperation("下载zip")
	public void downloadZip(HttpServletResponse response) {
		downloadService.downloadZip(response);
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值