java批量下载为zip

前言:

1.前端:

在这里插入代码片

2.后端

/**  批量下载为 zip  **/
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
public static void batchDownLoadFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){
		String filename = "ces";
		//需要下载的文件路径
		String[] filepath = new String[3];
		filepath[0] = "D:\\AA\\GG\\1565679467697.txt";
		filepath[1] = "D:\\AA\\GG\\22.txt";
		filepath[2] = "D:\\AA\\GG\\33.txt";

		//下载的文件名称
		String[] documentname = new String[3];
		documentname[0] = "1565679467697.txt";
		documentname[1] = "22.txt";
		documentname[2] = "33.txt";

		byte[] buffer = new byte[1024];
		Date date = new Date();
		//生成zip文件存放位置
		String strZipPath = "D:\\AA\\GG\\" + date.getTime() + ".zip";
		File file = new File("D:\\AA\\GG\\");
		if (!file.isDirectory() && !file.exists()) {
			file.mkdirs();
		}
		try {
			ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipPath));
			//必须设置编码格式。否则,中文会出现乱码。注意:如果该处报错,则是你导包有问题。应该是 org.apache.tools.zip.*里面的包。而不是util包
			out.setEncoding("gbk");
			// 需要同时下载的多个文件
			for (int i = 0; i < filepath.length; i++) {
				File f = new File(filepath[i]);
				FileInputStream fis = new FileInputStream(f);
				out.putNextEntry(new ZipEntry(documentname[i]));
				int len;
				// 读入需要下载的文件的内容,打包到zip文件
				while ((len = fis.read(buffer)) > 0) {
					out.write(buffer, 0, len);
				}
				out.closeEntry();
				fis.close();
			}
			out.close();
			DzFileGlAction.downLoadFile(request, response, strZipPath, filename + ".zip");
			File temp = new File(strZipPath);
			if (temp.exists()) {
				temp.delete();
			}
		} catch (Exception e) {
			System.out.println("文件下载错误");
		}
	}

3.浏览器弹框下载:

public static void downLoadFile(HttpServletRequest request, HttpServletResponse response, String filePath, String filename) {
		try {
			File file = new File(filePath);
			String userAgent = request.getHeader("User-Agent");
			if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
				filename = java.net.URLEncoder.encode(filename, "UTF-8");
			} else {
				filename = new String(filename.getBytes("utf-8"), "iso8859-1");
			}
			response.addHeader("Content-Disposition", "attachment;filename=" + filename);
			//response.setContentType("application/vnd.ms-excel");
			response.setContentType("multipart/form-data");
			byte[] b = new byte[1024];
			int len = 0;
			FileInputStream fs = new FileInputStream(file);
			PrintWriter writer = response.getWriter();
			while ((len = fs.read()) != -1) {
				writer.write(len);
			}
			fs.close();
			writer.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

贴图:
java批量下载为zip_第1张图片

java批量下载为zip_第2张图片

你可能感兴趣的:(技术栈)