您的位置:首页 > 其它

文件的打包压缩与下载

2013-12-19 09:45 260 查看
java代码:action方法

public  void zip(List<BbEntity list,String zipName,,String sourceName){

OutputStream o = null;

o = servletActionContext.getResponse().getOutputStream();//将输出流写入到服务器的响应输出流里。

response.setHeader("","attachement;filename='xx.zip'");//对下载的文件重命名

ZipOutputStream out =new ZipOutputStream(o);

//ZipOutputStream out =new ZipOutputStream(new File(zipName));//将输出流写入到指定的zip文件里。

for(int i=0;i<list.size();i++){

BbEntity bb = list.get(i);

out.putNextEntry(new ZipEntry(bb.getDisplayPath()+"/"+bb.getFileName));

FileInputStream in = new FileInputStream(new File(bb.getRealPath()));

int b;

while((b=in.read())!=-1){

out.write(b);

}

in.close();

}

out.close();

}

}

}

调用方式:zip(getBbList(),"d:/xx.zip","d:/xx")

页面调用方式:window.location = '${pagecontext.request.contextPath}/xx/yy!zip.action'

页面展示:弹出一个下载对话框。

将upload文件写到指定的path,文件名为filename

 public static void saveFileFromInputStream(File upload,String path,String filename) throws IOException

    {      

        InputStream in = null;

        OutputStream out = null;

        try {

            in = new BufferedInputStream(new FileInputStream(upload));

            out = new BufferedOutputStream(new FileOutputStream(path + "/"

                    + filename));

            byte[] buffer = new byte[BUFFER_SIZE];

            int byteread = 0;

            while ((byteread = in.read(buffer)) != -1) {

                out.write(buffer, 0, byteread);

                out.flush();

            }

        } catch (Exception e) {

            e.printStackTrace();

        }finally{

            in.close();

            out.close();

        }

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: