简介
传统文件打包方式为,服务器文件进行压缩,然后进行下载,会占用一定的服务器资源。
以下代码实现了服务器文件打zip包,实现了边压缩打包边下载,针对的时zip包,本人因工作项目所写,亲测可用。
@RequestMapping(value = "zip/export/{}")
public void zipExport(HttpServletRequest request, HttpServletResponse reponse){
//zip包的名称
String zipName = "package.zip";
//要打包的文件夹路径
String packagePath = " ";
response.setContentType("octets/stream");
response.setCharacterEncoding("UTF-8");
String agent = request.getHeader("USER-AGENT");
try{
if(agent.contains("MSIE") || agent.contains("Trident")){
zipName = URLEncoder.encode(zipName, "UTF-8");
}else{
zipName = new String(zipName.getBytes("UTF-8"), “ISO-8859-1”);
}
}catch(UnsupportedEncodingException e){
logger.error(e.getMessage(), e);
}
response.setHeader("Content-Disposition", "attachment;fileName=\"" + zipName + "\"");
ZipOutputStream zipos = null;
try {
zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
zipos.setMethod(ZipOutputStream.DEFLATED);
zipos.setLevel(0);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
DataOutputStream os = null;
InputStream is = null;
try {
String[] fileNameList = new File(path).list();
for(int i = 0; i < fileNameList.length; i++ ){
File file = new File(packagePath+ File.separator + fileNameList[i]);
zipos.putNextEntry(new ZipEntry(fileNameList[i]));
os = new DataOutputStream(zipos);
is = new FileInputStream(file);
//输入流转换为输出流
IOUtils.copy(is, os);
is.close();
zipos.closeEntry();
}
} catch (IOException e) {
logger.error(e.getMessage(), e);
}finally {
// 推荐使用try-with-resource
if (is != null) {
is.close();
}
if(os != null){
os.flush();
os.close();
}
if (zipos != null) {
zipos.flush();
zipos.close();
}
}
}
本文章系博主原创,尊重博主辛劳成果,转载请注明出处,谢谢。