posts - 241,  comments - 116,  trackbacks - 0
功能:zip文件下载
简述:
1.根据画面上的复选框进行文件打包下载
2.待下载文件保存在服务器的硬盘上,打包过程中不生成临时文件
3.打包过程中需要动态创建一个txt文件一并打进zip包中
4.页面上没有文件被选择的场合,按下【下载】按钮后,什么都不做(不刷新页面)

部分内容参考自互联网,如果错误,欢迎指正。
Struts配置文件
<!-- 数据下载Action -->
<action name="downZip" class="DownloadAction">
    <result name="nodata" type="httpheader">
        <param name="status">sky7034</param>
    </result>
</action>
Action代码
    private OutputStream res;
    private ZipOutputStream zos;

    // action的主方法
    public String execute() throws Exception {
        
        if (有数据可下载) {;
            // 预处理
            preProcess();

        } else {
            // 没有文件可下载的场合,返回nodata,设定参照struts配置文件
            return "nodata";
        }

        // 在这里编辑好需要下载的数据风之境地
        // 文件可以是硬盘上的
        // 文件也可以是自己写得数据流,如果是自己写得数据流,请参看outputZipFile方法中的【2.】
        File file = new File();
        file = ...
        outputZipFile(file);
        
        // 后处理
        afterProcess();
        
        return null;

    }

    // 预处理
    public void preProcess() throws Exception {
        
        HttpServletResponse response = ServletActionContext.getResponse();
        
        res = response.getOutputStream();

        //清空输出流
        response.reset();   

        //设定输出文件头
        response.setHeader("Content-disposition ","attachment; filename=a.zip ");   
        response.setContentType("application/zip");
        zos = new ZipOutputStream(res);
        
    }

    // 后处理
    public void afterProcess() throws Exception {
        zos.close();
        res.close();
    }

    // 写文件到客户端
    private void outputZipFile(File file) throws IOException, FileNotFoundException {
        ZipEntry ze = null;
        byte[] buf = new byte[1024];
        
        int readLen = 0;
        
        // 1.动态压缩一个File到zip中
        // 创建一个ZipEntry,并设置Name和其它的一些属性
        // 压缩包中的路径和文件名称
        ze = new ZipEntry("1\\1\\" + file.getName());
        ze.setSize(file.length());
        ze.setTime(file.lastModified());

        // 将ZipEntry加到zos中,再写入实际的文件内容
        zos.putNextEntry(ze);
        InputStream is = new BufferedInputStream(new FileInputStream(file));

        // 把数据写入到客户端
        while ((readLen = is.read(buf, 0, 1024)) != -1) {
            zos.write(buf, 0, readLen);
        }
        is.close();
        
        // 2.动态压缩一个String到zip中
        String customFile = "This is a text file.";

        // 压缩包中的路径和文件名称
        ZipEntry cze = new ZipEntry(“1\\1\\” + "Test.txt");
        zos.putNextEntry(cze);

        // 利用ByteArrayInputStream把流数据写入到客户端
        is = new ByteArrayInputStream(customFile.getBytes());
        while ((readLen = is.read(buf, 0, 1024)) != -1) {
            zos.write(buf, 0, readLen);
        }
        
    }
posted on 2012-01-10 09:12 墙头草 阅读(3539) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航:
 
人人游戏网 软件开发网 货运专家