1.代码
package com.w4xj.newStart.io.download;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@Controller
public class ZipDownloadController {
@GetMapping("/zipDownlaod/download/{ids}")
public void zipDownload(HttpServletRequest request, HttpServletResponse response, @PathVariable("ids") String ids) {
String exceptionString = "------------------下载结果报告-------------------------\r\n";
String[] idArray = ids.split(",");
ZipOutputStream zop = null;
String zipName = "批量下载demo.zip";
try {
//火狐浏览器自己会对URL进行一次URL转码,所以区别处理
if (request.getHeader("user-agent").toLowerCase().indexOf("firefox") > -1) {
zipName = new String(zipName.getBytes("UTF-8"), "ISO-8859-1");
}else {//其他浏览器,正常utf-8编码即可
zipName = URLEncoder.encode(zipName, "UTF-8");
}
response.setHeader("Content-Disposition", "attachment; filename=\"" + zipName + "\"");
response.setContentType("application/octet-stream;charset=UTF-8");
response.setCharacterEncoding("utf-8");
zop = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
zop.setMethod(ZipOutputStream.DEFLATED);
for(int k = 0; k < idArray.length; k++) {
FileInputStream fis;
String filename = idArray[k] + ".txt";
try {
fis = new FileInputStream(new File("G:\\tempDir\\" + filename));
zop.putNextEntry(new ZipEntry(filename));
byte[] bs = new byte[1024];
int len = -1;
while((len = fis.read(bs)) != -1) {
zop.write(bs, 0, len);
}
zop.closeEntry();
if(null != fis) {
fis.close();
}
} catch (FileNotFoundException e) {
System.out.println(filename + "---文件未找到");
exceptionString += filename + "---文件未找到\r\n";
//日志记录
e.printStackTrace();
continue;
} catch (IOException e) {
System.out.println(filename + "---写入异常");
exceptionString += filename + "---写入异常\r\n";
//日志记录
e.printStackTrace();
}
}
zop.putNextEntry(new ZipEntry("-^_^-下载结果报告.txt"));
byte[] bs = exceptionString.getBytes();
zop.write(bs);
zop.closeEntry();
} catch (IOException e1) {
System.out.println("读写异常---" + zipName);
//日志记录
e1.printStackTrace();
} finally {
if(null != zop) {
try {
zop.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
2.效果