读书人

struts2 动态压缩成zip文件上载(不生

发布时间: 2012-09-02 21:00:34 作者: rapoo

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

部分内容参考自互联网,如果错误,欢迎指正。

Struts配置文件

<!-- 数据下载Action --><action name="downZip" type="httpheader"><param name="status">204</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);}}


读书人网 >编程

热点推荐