private static final int BUFFER_SIZE = 1024;
//压缩多个文件为ZIP格式
public static void toZip(List<File> srcFiles ,String path,HttpServletResponse response)throws RuntimeException, IOException {
FileOutputStream fileOutputStream=new FileOutputStream(path);
long start = System.currentTimeMillis();
ZipOutputStream zos = null ;
try {
zos = new ZipOutputStream(fileOutputStream);
for (File srcFile : srcFiles) {
byte[] buf = new byte[BUFFER_SIZE];
zos.putNextEntry(new ZipEntry(srcFile.getName()));
int len;
FileInputStream in = new FileInputStream(srcFile);
while ((len = in.read(buf)) != -1){
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
}
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) +" ms");
} catch (Exception e) {
e.printStackTrace();
}finally{
if(zos != null){
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Tools.downfile(path, "照片.zip", response);
}
//下载文件
public static void downfile(String path,String filename,HttpServletResponse response) throws IOException{
response.setContentType("application/x-msdownload");
response.addHeader("Content-Disposition","attachment;fileName="+new String(filename.getBytes(),"iso8859-1"));
OutputStream os = response.getOutputStream();
FileInputStream fis = new FileInputStream(path);
try{
BufferedInputStream bufferedInputStream=new BufferedInputStream(fis);
BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(os);
byte[] buffer = new byte[4096];
int count = 0;
while ((count=bufferedInputStream.read(buffer, 0, buffer.length))>0) {
bufferedOutputStream.write(buffer, 0, count);
}
bufferedInputStream.close();
bufferedOutputStream.flush();
bufferedOutputStream.close();
os.close();
fis.close();
}catch(Exception e){
e.printStackTrace();
}
}