步骤:
把全需要打包的数据获取路径,到数据发布在web服务器里的路径。
public String download(){ // endIdSets是文件所在路径的集合 String fileName="zip下载包.zip"; // 用于创建文件夹 String folderName=new Date().getTime()+"_ZIP"; response.setContentType("Content-Disposition;charset=GB2312"); response.setHeader("Content-Disposition", "attachment;" + " filename="+ new String(fileName.getBytes(), "ISO-8859-1")); String realpathdir = request.getSession().getServletContext().getRealPath("");//获取上下文路径 System.out.println(realpathdir); byte[] buffer = new byte[8192]; ZipOutputStream out = new ZipOutputStream(response.getOutputStream()); String fileRealPath=null; for (String idAddress : endIdSets) { fileRealPath=idAddress.substring(idAddress.indexOf("/"), idAddress.lastIndexOf("/")); File tempfile = creatTempFile((realpathdir+idAddress.replace('/', '//')),folderName); FileInputStream fis = new FileInputStream(tempfile); out.putNextEntry(new ZipEntry(tempfile.getName())); int len; while ((len = fis.read(buffer)) > 0) { out.write(buffer, 0, len); } out.closeEntry(); fis.close(); } out.flush(); out.close(); FileUtils.deleteDirectory(realpathdir.replace('/', '//')+fileRealPath+File.separator+folderName); return null; } return null; }
/imgData/ALS/2011-02/image11-02-14_15-30-01-67.jpg public File creatTempFile(String filePathAndName,String folderName) throws IOException { String fileName = filePathAndName.substring(filePathAndName.lastIndexOf("//")+1, filePathAndName.length()); String filePath = filePathAndName.substring(0, filePathAndName.lastIndexOf("//")); File folder = new File(filePath+File.separator+folderName+File.separator); if (!folder.exists()) { folder.mkdirs(); } File tempfile = new File(filePath+File.separator+folderName+File.separator+fileName); tempfile.createNewFile(); byte[] BUFFER_SIZE = new byte[8192]; File files=new File(filePathAndName); InputStream in = new BufferedInputStream(new FileInputStream(files), 1024); OutputStream out = new BufferedOutputStream(new FileOutputStream(tempfile), 1024); while (in.read(BUFFER_SIZE) > 0) { out.write(BUFFER_SIZE); } out.close(); in.close(); return tempfile; }