Java 多个文件压缩下载

2018/03/06 16:38
阅读数 22

有时候会有多个附件一起下载的需求,这个时候最好就是打包下载了 首先下面这段代码是正常的单个下载

public void Download(@RequestParam("file_path") String file_path, HttpServletResponse response) {
		logger.info("try to download  file, the filePath : " + file_path);
        int i = file_path.lastIndexOf("/");
        String filename = file_path.substring(i+1);
		try {
           BufferedInputStream in=new BufferedInputStream(ossFileUtil.getFile(file_path));
           BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
			//通知浏览器以附件形式下载
			response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(filename,"utf-8"));
           byte[] car=new byte[1024];
           int L=0;
           while((L=in.read(car))!=-1){
               out.write(car, 0,L);
           }
           if(out!=null){
               out.flush();
               out.close();
           }
           if(in!=null){
               in.close();
           }
		} catch (IOException e) {
			logger.error("the download file error :" + e.getMessage());
			throw new ErrorException("200003", errorMsgUtils.errorMsg("","200003"));
		}
    }

下面代码是打包下载

    public void serverDownloads(@RequestParam("file_path") String file_path,
								@RequestParam(name = "download_name", required = false) String download_name,
								HttpServletResponse response) throws IOException {
		logger.info("try to download server file, the filePath : " + file_path);
		String[] paths = file_path.split(",\\$\\$,");
		if(paths.length > 1){
			// 打包的文件名
			String packageName;
			if (download_name != null && download_name.trim().length() > 0) {
				packageName = download_name + ".zip";
			} else {
				packageName = "file.zip";
			}
			//打包下载
			response.setContentType("APPLICATION/OCTET-STREAM");
//			response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(packageName,"utf-8"));
			response.setHeader("Content-Disposition","attachment;filename=" + packageName);
			ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
			try {
				int j = 1;
				for(String path : paths){
					int i = path.lastIndexOf("/");
					String filename = path.substring(i+1);
					ZipUtils.doZip(remoteFileUtil.getFile(path), out, filename);
					response.flushBuffer();
					j++;
				}
			} catch (IOException e) {
				logger.error("the download file error :" + e.getMessage());
				throw new ErrorException("200003", errorMsgUtils.errorMsg("","200003"));
			}finally{
		          out.close();
		    }
		}else{
	        int i = file_path.lastIndexOf("/");
	        String filename = file_path.substring(i+1);
			try {
				BufferedInputStream in=new BufferedInputStream(remoteFileUtil.getFile(file_path));    //BufferedInputStream(InputStream in)
				BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
				//通知浏览器以附件形式下载
//				response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(filename,"utf-8"));
				response.setHeader("Content-Disposition","attachment;filename=" + filename);
				byte[] car=new byte[1024];
				int L=0;
				while((L=in.read(car))!=-1){
				   out.write(car, 0,L);
				}
				if(out!=null){
				   out.flush();
				   out.close();
				}
				if(in!=null){
				   in.close();
				}
			} catch (IOException e) {
				logger.error("the download file error :" + e.getMessage());
				throw new ErrorException("200003", errorMsgUtils.errorMsg("","200003"));
			}
		}
    }

最后是ZipUtils类内容

public class ZipUtils {
    
	  private ZipUtils(){
	    }
	    
	    public static void doCompress(String srcFile, String zipFile) throws IOException {
	        doCompress(new File(srcFile), new File(zipFile));
	    }
	    
	    /**
	     * 文件压缩
	     * @param srcFile 目录或者单个文件
	     * @param zipFile 压缩后的ZIP文件
	     */
	    public static void doCompress(File srcFile, File zipFile) throws IOException {
	        ZipOutputStream out = null;
	        try {
	            out = new ZipOutputStream(new FileOutputStream(zipFile));
	            doCompress(srcFile, out);
	        } catch (Exception e) {
	            throw e;
	        } finally {
	            out.close();//记得关闭资源
	        }
	    }
	    
	    public static void doCompress(String filelName, ZipOutputStream out) throws IOException{
	        doCompress(new File(filelName), out);
	    }
	    
	    public static void doCompress(File file, ZipOutputStream out) throws IOException{
	        doCompress(file, out, "");
	    }
	    
	    public static void doCompress(File inFile, ZipOutputStream out, String dir) throws IOException {
	        if ( inFile.isDirectory() ) {
	            File[] files = inFile.listFiles();
	            if (files!=null && files.length>0) {
	                for (File file : files) {
	                    String name = inFile.getName();
	                    if (!"".equals(dir)) {
	                        name = dir + "/" + name;
	                    }
	                    ZipUtils.doCompress(file, out, name);
	                }
	            }
	        } else {
	             ZipUtils.doZip(inFile, out, dir);
	        }
	    }
	    
	    public static void doZip(File inFile, ZipOutputStream out, String dir) throws IOException {
	        String entryName = null;
	        if (!"".equals(dir)) {
	            entryName = dir + "/" + inFile.getName();
	        } else {
	            entryName = inFile.getName();
	        }
	        ZipEntry entry = new ZipEntry(entryName);
	        out.putNextEntry(entry);
	        
	        int len = 0 ;
	        byte[] buffer = new byte[1024];
	        FileInputStream fis = new FileInputStream(inFile);
	        while ((len = fis.read(buffer)) > 0) {
	            out.write(buffer, 0, len);
	            out.flush();
	        }
	        out.closeEntry();
	        fis.close();
	    }
	    
	    //
	    public static void doZip(InputStream inputStream, ZipOutputStream out, String entryName) throws IOException {
//	        String entryName = null;
//	        if (!"".equals(dir)) {
//	            entryName = dir + "/" + inFile.getName();
//	        } else {
//	            entryName = inFile.getName();
//	        }
	        ZipEntry entry = new ZipEntry(entryName);
	        out.putNextEntry(entry);
	        
	        int len = 0 ;
	        byte[] buffer = new byte[1024];
//	        FileInputStream fis = new FileInputStream(inFile);
	        while ((len = inputStream.read(buffer)) > 0) {
	            out.write(buffer, 0, len);
	            out.flush();
	        }
	        out.closeEntry();
	        inputStream.close();
	    }
	    
	    public static void main(String[] args) throws IOException {
	        doCompress("G:/test/", "G:/java.zip");
	    }
	    
}
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部