欢迎大家来到IT世界,在知识的湖畔探索吧!
package com.hst.web.common.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DownloadUtil {
private static Logger logger = LoggerFactory.getLogger(DownloadUtil.class);
/**
*页面传压缩的多个文件
* @param pdfs文件列表
* @param response
* @throws IOException
*/
public static void exportZIP(List<File> pdfs, String zipFileName, HttpServletResponse response) throws IOException {
if(null == pdfs || 0 == pdfs.size())
return;
ServletOutputStream os = null;
ZipOutputStream zipOS = null;
try {
os = getOutputStream(zipFileName, response);
zipOS = new ZipOutputStream(os);
for (File file : pdfs) {// 将pdf文件发送到客户端
ZipEntry entry = new ZipEntry(file.getName());
zipOS.putNextEntry(entry);
try(FileInputStream fis = new FileInputStream(file)){
IOUtils.copy(fis, zipOS);
}
}
zipOS.flush();
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (null != zipOS)
zipOS.close();
if (null != os)
os.close();
}
}
/**
* 打开response输出流
* @param string
* @param response
* @return
* @throws IOException
*/
public static ServletOutputStream getOutputStream(String fileName, HttpServletResponse response) throws IOException {
response.setHeader(“Content-Disposition”,
StringUtils.join(“attachment;filename=”, URLEncoder.encode(fileName, “UTF-8”)));
response.setHeader(“Connection”, “close”);
response.setHeader(“Content-Type”, “application/octet-stream”);
return response.getOutputStream();
}
}
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://itzsg.com/35049.html