java下载压缩包简化代码

	/**
	 * 批量打包下载文件生成zip文件下载
	 * 
	 */
	@CrossOrigin
	@RequestMapping(value = "/xiazai", method = RequestMethod.GET)
	public ResponseDto downloadFiles(HttpServletRequest request, HttpServletResponse response, String x)
			throws ServletException, IOException {
		try {
			List<String> filePaths = xManager.getRealPaths(x);
			List<File> files = FileUtil.getFiles(filePaths);
			if (files == null || files.isEmpty()) {
				return new ResponseDto(HttpStatus.INTERNAL_SERVER_ERROR, "无可下载文件");
			}
			CustomFileUtil.downLoadZipFile(files, response);
			return null;
		} catch (Exception e) {
			logger.error("downloadFiles  error :", e.getMessage(), e);
			return new ResponseDto(HttpStatus.INTERNAL_SERVER_ERROR, "下载失败");
		}
	}



package com.x;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CustomFileUtil {
	private static Logger logger = LoggerFactory.getLogger(CustomFileUtil.class);

	public static List<File> getFiles(List<String> filePaths) {
		List<File> files = new ArrayList<File>();
		if (filePaths == null || filePaths.isEmpty()) {
			return null;
		}
		for (String t : filePaths) {
			if (t == null || ("").equals(t)) {
				continue;
			}
			File temp = new File(t);
			if (temp.exists()) {
				files.add(temp);
			}
		}
		if (files == null || files.isEmpty()) {
			return null;
		}
		return files;
	}

	/**
	 * 将文件写入到zip文件中
	 * 
	 * @param inputFile
	 * @param outputstream
	 * @throws Exception
	 */
	public static void zipFile(File inputFile, ZipOutputStream outputstream) {
		FileInputStream inStream = null;
		BufferedInputStream bInStream = null;
		try {
			if (inputFile.isFile()) {
				inStream = new FileInputStream(inputFile);
				bInStream = new BufferedInputStream(inStream);
				ZipEntry entry = new ZipEntry(inputFile.getName());
				outputstream.putNextEntry(entry);
				byte[] buffer = new byte[2 * 1024 * 1024];
				int byteRead = 0;
				while ((byteRead = bInStream.read(buffer)) != -1) {
					outputstream.write(buffer, 0, byteRead);
				}
				outputstream.closeEntry(); // Closes the current ZIP entry
			}
		} catch (IOException e) {
			logger.error("zipFile IOException error:", e.getMessage(), e);
		} finally {
			try {
				if (bInStream != null) {
					bInStream.close();// 关闭
				}
				if (inStream != null) {
					inStream.close();
				}
			} catch (IOException e) {
			}
		}
	}

	/**
	 * 打包压缩下载文件
	 */
	public static void downLoadZipFile(List<File> files, HttpServletResponse response) throws IOException {
		String zipName = UUID.randomUUID().toString() + ".zip"; // 在服务器端创建打包下载的临时文件
		response.setContentType("APPLICATION/OCTET-STREAM");
		response.setHeader("Content-Disposition", "attachment; filename=" + zipName);
		ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
		try {
			for (int i = 0; i < files.size(); i++) {
				File file = (File) files.get(i);
				if (file.exists()) {
					zipFile(file, out);
					response.flushBuffer();
				}
			}
		} catch (Exception e) {
			logger.error("downLoadZipFile error: ", e.getMessage(), e);
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值