将多个文件进行压缩打包并下载,以及解决文件名下载后的乱码问题

文件地址可以是网络地址,也可以是绝对路径的文件路径,均可实现下载多个文件并打包压缩,如果需要更改下载后的文件名可根据自己的业务自行调整代码

package org.springblade.course.util;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Slf4j
public class FileUtils {

	//url转file
	private File getFileByUrl(String fileUrl) {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		BufferedOutputStream stream = null;
		InputStream inputStream = null;
		File file = null;
		try {
			URL imageUrl = new URL(fileUrl);
			HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
			conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
			inputStream = conn.getInputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = inputStream.read(buffer)) != -1) {
				outStream.write(buffer, 0, len);
			}
			file = File.createTempFile("file", fileUrl.substring(fileUrl.lastIndexOf("."), fileUrl.length()));
			FileOutputStream fileOutputStream = new FileOutputStream(file);
			stream = new BufferedOutputStream(fileOutputStream);
			stream.write(outStream.toByteArray());
		} catch (Exception e) {
		} finally {
			try {
				if (inputStream != null) {
					inputStream.close();
				}
				if (stream != null) {
					stream.close();
				}
				outStream.close();
			} catch (Exception e) {
			}
		}
		return file;
	}

	/**
	 * 将多个文件进行压缩打包,解决文件名下载后的乱码问题
	 */
	public void downloadAllFile(HttpServletRequest request, HttpServletResponse response, List<String> files, String zipName) throws UnsupportedEncodingException {
		String downloadName = zipName + ".zip";
		String userAgent = request.getHeader("User-Agent");
		// 针对IE或者以IE为内核的浏览器:
		if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
			downloadName = java.net.URLEncoder.encode(downloadName, "UTF-8");
		} else {
			// 非IE浏览器的处理:
			downloadName = new String(downloadName.getBytes("UTF-8"), "ISO-8859-1");
		}
		//经过上面的名称处理即可解决文件名下载后乱码的问题
		response.setContentType("multipart/form-data");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", downloadName));
		OutputStream outputStream = null;
		ZipOutputStream zos = null;
		try {
			outputStream = response.getOutputStream();
			zos = new ZipOutputStream(outputStream);
			// 将文件流写入zip中
			downloadTolocal(zos, files);
		} catch (IOException e) {
			log.error("downloadAllFile-下载全部附件失败", e);
		} finally {
			if (zos != null) {
				try {
					zos.close();
				} catch (Exception e2) {
					log.info("关闭输入流时出现错误", e2);
				}
			}
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (Exception e2) {
					log.info("关闭输入流时出现错误", e2);
				}
			}
		}
	}

	private void downloadTolocal(ZipOutputStream zos, List<String> files) throws IOException {
		//获取文件信息
		//将资源表list循环出取得路径以及文件名,然后放进ZipEntry中再执行下载
		for (String path : files) {
			InputStream is = null;
			BufferedInputStream in = null;
			byte[] buffer = new byte[1024];
			int len;
			String[] strs = path.split("/");
			//创建zip实体(一个文件对应一个ZipEntry)
			ZipEntry entry = new ZipEntry(strs[strs.length - 1]);
			try {
				//获取需要下载的文件流
				File file = new File(path);
				if (!file.exists()) {
				//如果是网络地址可以通过网络地址获取文件
					file = this.getFileByUrl(path);
					if (!file.exists()) {
						continue;
					}
				}
				is = new FileInputStream(file);
				in = new BufferedInputStream(is);
				zos.putNextEntry(entry);
				//文件流循环写入ZipOutputStream
				while ((len = in.read(buffer)) != -1) {
					zos.write(buffer, 0, len);
				}
			} catch (Exception e) {
				log.info("下载压缩文件出错", e);
			} finally {
				if (entry != null) {
					try {
						zos.closeEntry();
					} catch (Exception e2) {
						log.info("下载全部附件--zip实体关闭失败", e2);
					}
				}
				if (in != null) {
					try {
						in.close();
					} catch (Exception e2) {
						log.info("下载全部附件--文件输入流关闭失败", e2);
					}
				}
				if (is != null) {
					try {
						is.close();
					} catch (Exception e) {
						log.info("下载全部附件--输入缓冲流关闭失败", e);
					}
				}
			}
		}
	}
}

效果图:
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值