文章标签 ‘FilePool’
20144 月16

Nutz:结合文件池实现网络下载文件,压缩成zip后下载

入口函数:
@At
public void downImage(@Param(“tvid”) int tvid, HttpServletResponse resp, HttpServletRequest req) {

}

使用Nutz文件池:

Globals.FILE_POOL= new NutFilePool(“~/tmp/myfiles”, 10);

源码:

int i = 0;
            File f = Globals.FILE_POOL.createFile(".zip");
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(f.getAbsolutePath()));
            for (Weixin_image image : list) {
                i++;
                String filename = Strings.sNull(bbinfo.get(image.getUid())) + "_" + Strings.sNull(userinfo.get(image.getUid())) + "_" + i+".jpg";
                String picurl = image.getPicurl();
                if (!Strings.isBlank(image.getImage_url())) {
                    picurl = image.getImage_url();
                }
                URL url = new URL(picurl);
                try {
                    URLConnection conn = url.openConnection();
                    InputStream inStream = conn.getInputStream();
                    byte[] buffer = new byte[1204];
                    out.putNextEntry(new ZipEntry(filename));
                    while ((byteread = inStream.read(buffer)) != -1) {
                        bytesum += byteread;
                        out.write(buffer, 0, byteread);
                    }
                    out.closeEntry();
                    inStream.close();

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            out.close();
            resp.setHeader("Content-Length", "" + f.length());
            resp.setHeader("Content-Disposition", "attachment; filename=\"" + tvShow.getPlay_name() + ".zip\"");
            Streams.writeAndClose(resp.getOutputStream(), Streams.fileIn(f));