java下载多个文件文件

第一步 将要下载的多个文件打包成ZIP格式

public String makeZip(List<String> path) throws IOException{

byte[] buffer = new byte[1024];

//创建压缩包路径

String strZipName = "c:/Demo.zip";

ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipName));

for(String str:path){

FileInputStream fis = new FileInputStream(file1[i]);

out.putNextEntry(new ZipEntry(str.getName()));

int len;

while((len = fis.read(buffer))>0) {

out.write(buffer,0,len);

}

out.closeEntry();

fis.close();

}

out.close();

return strZipName;

}

第二步 普通的下载

File file = new File(realpath );

String filename = file.getName();

ServletOutputStream out;

response.setContentType("multipart/form-data");

response.setHeader("Content-Disposition", "attachment;fileName="+new String(filename.getBytes("gbk"), "iso-8859-1"));

try {

FileInputStream inputStream = new FileInputStream(file);

//3.通过response获取ServletOutputStream对象(out)

out = response.getOutputStream();

int b = 0;

byte[] buffer = new byte[512];

while ((b=inputStream.read(buffer))>0){

//4.写到输出流(out)中

out.write(buffer,0,b);

}

inputStream.close();

out.close();

out.flush();

} catch (IOException e) {

e.printStackTrace();

}