java多文件打包下载-java下载文件

java多文件打包下载-java下载文件

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();

}

}

推荐阅读