//Controller层
@RequestMapping(value="/downLoadZip")
public void downLoadZip(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String gid =request.getParameter("gid");
List filelist = sbjhService.getFileList(gid);
String realPath = request.getServletContext().getRealPath("/");//文件保存时候的根路径
try {
FileInputStream []inputs= new FileInputStream [filelist.size()];
String []names = new String [filelist.size()];
for(int i=0;i<inputs.length;i++){
Map map = (Map) filelist.get(i);
inputs[i]=new FileInputStream(new File(realPath+map.get("PATH")));
names[i] = map.get("FILENAME")+"";
}
File zipFile = new File("压缩包下载路径");// 压缩包下载路径
byte[] buf = new byte[1024];
int len;
ZipOutputStream zout=new ZipOutputStream(new FileOutputStream(zipFile));
zout.setEncoding("GBK");
for (int i = 0; i < inputs.length; i++) {
FileInputStream in =inputs[i];
zout.putNextEntry(new ZipEntry(names[i]));
while ((len = in.read(buf)) > 0) {
zout.write(buf, 0, len);
}
zout.closeEntry();
in.close();
}
zout.close();
//下载
FileInputStream zipInput =new FileInputStream(zipFile);
OutputStream out = response.getOutputStream();
response.setContentType("application/octet-stream;charset=GBK");
response.setHeader("Content-Disposition", "attachment; filename=download.zip");
response.setCharacterEncoding("GBK");
while ((len=zipInput.read(buf))!= -1){
out.write(buf,0,len);
}
zipInput.close();
out.flush();
out.close();
//删除压缩包
zipFile.delete();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Dao层
public List getFileList(String gid) {
String sql = "select filename,path from ky_sys_XGWD where dbh in (select gid From ky_main_xmsb where jhbh='"+gid+"')";
return db.queryForList(sql);
}
//jsp
$(document).on("click",".btn_downLoad",function(){
var gid = $(this).parents("tr").find("[name='gid']").val();
window.location.href="${pageContext.request.contextPath}/sbjh/downLoadZip?gid="+gid;
});
//包不要导错
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
//依赖jar包暂时不知道如何上传,附上名字
ant-1.4.1.jar