1.页面请求
<a href="#" class="btn btn-default" id="downZip" title="下载">下载</a>
$("#downZip").click(function(){
window.open("${ctx}/jss/jssProjectPrice/down");
});
2.controller:
@RequestMapping("/down")
public String down(HttpServletResponse response) throws Exception {
List files = new ArrayList();
File file1 = new File("D:\\test.pdf");
File file2 = new File("D:\\testZip.docx");
files.add(file1);
files.add(file2);
downLoadFiles(files, response);
return "成功";
}
public static HttpServletResponse downLoadFiles(List<File> files, HttpServletResponse response) throws Exception {
try {
String zipFilename = "D:/tempFile.zip";
File file = new File(zipFilename);
file.createNewFile();
if (!file.exists()) {
file.createNewFile();
}
response.reset();
FileOutputStream fous = new FileOutputStream(file);
ZipOutputStream zipOut = new ZipOutputStream(fous);
zipFile(files, zipOut);
zipOut.close();
fous.close();
return downloadZip(file, response);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
public static void zipFile(List files, ZipOutputStream outputStream) {
int size = files.size();
for (int i = 0; i < size; i++) {
File file = (File) files.get(i);
zipFile(file, outputStream);
}
}
public static void zipFile(File inputFile, ZipOutputStream ouputStream) {
try {
if (inputFile.exists()) {
if (inputFile.isFile()) {
FileInputStream IN = new FileInputStream(inputFile);
BufferedInputStream bins = new BufferedInputStream(IN, 512);
ZipEntry entry = new ZipEntry(inputFile.getName());
ouputStream.putNextEntry(entry);
int nNumber;
byte[] buffer = new byte[512];
while ((nNumber = bins.read(buffer)) != -1) {
ouputStream.write(buffer, 0, nNumber);
}
bins.close();
IN.close();
} else {
try {
File[] files = inputFile.listFiles();
for (int i = 0; i < files.length; i++) {
zipFile(files[i], ouputStream);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static HttpServletResponse downloadZip(File file, HttpServletResponse response) {
if (file.exists() == false) {
System.out.println("待压缩的文件目录:" + file + "不存在.");
} else {
try {
InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition",
"attachment;filename=" + new String(file.getName().getBytes("GB2312"), "ISO8859-1"));
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
File f = new File(file.getPath());
f.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return response;
}