下载ZIP压缩包(压缩多个文件)

下面的方法是将图片服务器或者文件服务器的多个文件,并压缩成zip包,提供下载功能


/**
 * 获取 文件 流
 * @param url
 * @return
 * @throws IOException
 */
private void getFile(String url ,ZipOutputStream zipOut ,String name) throws IOException{
    URL urlConet = new URL(url);
    HttpURLConnection con = (HttpURLConnection)urlConet.openConnection();
    con.setRequestMethod("GET");
    con.setConnectTimeout(4 * 1000);
    InputStream inStream = con .getInputStream();    //通过输入流获取图片数据
    ZipEntry entry = new ZipEntry(name);
    zipOut.putNextEntry(entry);
    byte[] buffer = new byte[inStream.available()];//available()是获取流中数据字节的最大长度
    int len = 0;
    while( (len=inStream.read(buffer)) != -1 ){
        zipOut.write(buffer, 0, len);
    }
    inStream.close();
}

@RequestMapping("zip")
public void downLoad(HttpServletResponse response){
    List files = new ArrayList();
    String url1 = "http://static.uat.daoyitong.com/group1/M00/00/92/wKjcYFxGiTyALL9rAABDKq_73-M333.jpg";
    String url2 = "http://static.uat.daoyitong.com/group1/M00/00/92/wKjcYFxGiTyAMnXWAARECj27C5Y947.jpg";
    files.add(url1);
    files.add(url2);
    String zipFilename = "tempFile.zip";
    File file = new File(zipFilename);
    try {
        file.createNewFile();
        if (!file.exists()) {
            file.createNewFile();
        }
        response.reset();
        // 创建文件输出流
        FileOutputStream fous = new FileOutputStream(file);
        ZipOutputStream zipOut = new ZipOutputStream(fous);
        int size = files.size();
        for (int i = 0; i < size; i++) {
            //单个文件的名称 文档的话后准就是.doc  
            String imgUrl = (String) files.get(i);
            getFile(imgUrl ,zipOut,"1"+i+".jpg");
        }
        zipOut.close();
        fous.close();
        // 以流的形式下载文件。
        InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");

        // 如果输出的是中文名的文件,在此处就要用URLEncoder.encode方法进行处理
        response.setHeader("Content-Disposition",
                "attachment;filename=" + new String(file.getName().getBytes("GB2312"), "ISO8859-1"));
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
    } catch (Exception e) {
        e.printStackTrace();
    }  finally {
        try {
            File f = new File(file.getPath());
            f.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
经验分享 程序员 微信小程序 职场和发展