Step1:导入支持jar包

  commons-fileupload-1.3.1.jar
  commons-io-2.4.jar
  jstl-1.2.jar
  standard-1.1.2.jar
  commons-compress-1.10.jar 文件压缩工具包

Step2:编写请求下载jsp

<script type="text/javascript" src="jquery-1.8.3.js"></script>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<h1>文件列表--多文件</h1>
<div>
<ul>
<c:forEach items="${filenames }" var="filename">
<li>
<input type="checkbox" value="${filename }" name="filename" class="chkli chk">      
<img alt="加载中..." src="/imgs/${filename }" width="100">      
<a href="upload_download/download_file.action?filename=${filename }">download</a>
</li>
</c:forEach>
<li>
<input type="checkbox" name="" value="" class="chkall chk">全选
<a href="upload_download/download_multi_file.action?params=''" class="download_all">download all</a>
</li>
</ul>
</div>
<script type="text/javascript">
$(function(){
$(".chk").on("click",function(){
var params = "" ;
var chklis = $(".chkli");
for (var i = 0; i < chklis.length; i++) {
if($(chklis[i]).attr("checked")){
params += $(chklis[i]).val() + ","
}
}
var href_path = $(".download_all").attr("href");
var href_path_params = href_path.split("=")[0] +"="+ params ;
var href_path_params = href_path_params.substring(0,href_path_params.length-1);
$(".download_all").attr("href",href_path_params);
});
});
</script>

Step3:编写action

package com.struts2.fileuplad.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletRequest;
import com.struts2.util.BaseAware;
import com.struts2.util.ZipFileUtil;
public class MultipartFileDownloadAction extends BaseAware {
private static final long serialVersionUID = -8551022600136584709L;
//前台传递过来多个文件拼接的字符串
private String params ;
public String getParams() {
return params;
}
public void setParams(String params) {
this.params = params;
}
private String filename;
public String getFilename() {
return filename ;
}
public void setFilename(String filename) throws UnsupportedEncodingException {
this.filename = filename;
}
@Override
public String execute() {
return SUCCESS;
}
//该方法被对应的请求action中result的参数调用
//即:<param name="contentDisposition">attachment;fileName="${downloadFileName}"</param>
public String getDownloadFileName() throws UnsupportedEncodingException{
//使用指定的字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
// 构造一个新的 String,运用指定的字符集解码指定的字节数组。
//这里本该设置为UTF-8 但是IE依然显示乱码 换成GBK之后基本可以全部兼容了,有问题可以再修改
return this.filename = new String(filename.getBytes("GBK"),"ISO-8859-1");
}
private HttpServletRequest request;
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
//该方法被对应的请求action中result的参数调用
//即:<param name="inputName">inputStream</param>
public InputStream getInputStream() throws FileNotFoundException, UnsupportedEncodingException {
filename = request.getServletContext().getInitParameter("struts2_upload_imgs_path") +File.separator + "struts2-多个文件下载-" + new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(System.currentTimeMillis()) + ".zip" ;
/**
* 注意:::这个功能点应该添加一个拦截器 处理params为null或者""问题
*/
if(params != null && !"".equals(params)) {
//将多个附件的路径取出
String[] attachmentPathArray = params.split(",");
if(attachmentPathArray != null && attachmentPathArray.length >0) {
File[] files = new File[attachmentPathArray.length];
for(int i=0;i<attachmentPathArray.length;i++) {
if(attachmentPathArray[i] != null) {
File file = new File(
request.getServletContext().getInitParameter("struts2_upload_imgs_path")
+File.separator
+attachmentPathArray[i].trim());
if(file.exists()) {
files[i] = file;
}
}
}
System.out.println("getDownloadFileName-----"+filename);
//将多个附件压缩成zip
ZipFileUtil.compressFiles2Zip(files,filename);
}
}
File file = new File(filename);
FileInputStream fis = new FileInputStream(file);
return fis;
}
}

Step4:配置struts.xml

<action name="download_multi_file" class="com.struts2.fileuplad.action.MultipartFileDownloadAction">
<result type="stream">
<param name="contentType">application/octet-stream</param>
<param name="contentDisposition">attachment;fileName="${downloadFileName}"</param>
<param name="inputName">inputStream</param>
<param name="bufferSize">1024</param>
</result>
</action>

Step5:处理文件压缩工具类

package com.struts2.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.Zip64Mode;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
/**
* Zip文件工具类
*/
public class ZipFileUtil {
/**
* 把文件压缩成zip格式
* @param files 需要压缩的文件
* @param zipFilePath 压缩后的zip文件路径 ,如"D:/test/aa.zip";
*/
public static void compressFiles2Zip(File[] files,String zipFilePath) {
if(files != null && files.length >0) {
if(isEndsWithZip(zipFilePath)) {
ZipArchiveOutputStream zaos = null;
try {
File zipFile = new File(zipFilePath);
zaos = new ZipArchiveOutputStream(zipFile);
//Use Zip64 extensions for all entries where they are required
zaos.setUseZip64(Zip64Mode.AsNeeded); //将每个文件用ZipArchiveEntry封装
//再用ZipArchiveOutputStream写到压缩文件中
for(File file : files) {
if(file != null) {
ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(file,file.getName());
zaos.putArchiveEntry(zipArchiveEntry);
InputStream is = null;
try {
is = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[1024 * 5];
int len = -1;
while((len = is.read(buffer)) != -1) {
//把缓冲区的字节写入到ZipArchiveEntry
zaos.write(buffer, 0, len);
}
//Writes all necessary data for this entry.
zaos.closeArchiveEntry();
}catch(Exception e) {
throw new RuntimeException(e);
}finally {
if(is != null)
is.close();
} }
}
zaos.finish();
}catch(Exception e){
throw new RuntimeException(e);
}finally {
try {
if(zaos != null) {
zaos.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
} /**
* 把zip文件解压到指定的文件夹
* @param zipFilePath zip文件路径, 如 "D:/test/aa.zip"
* @param saveFileDir 解压后的文件存放路径, 如"D:/test/"
*/
public static void decompressZip(String zipFilePath,String saveFileDir) {
if(isEndsWithZip(zipFilePath)) {
File file = new File(zipFilePath);
if(file.exists()) {
InputStream is = null;
//can read Zip archives
ZipArchiveInputStream zais = null;
try {
is = new FileInputStream(file);
zais = new ZipArchiveInputStream(is);
ArchiveEntry archiveEntry = null;
//把zip包中的每个文件读取出来
//然后把文件写到指定的文件夹
while((archiveEntry = zais.getNextEntry()) != null) {
//获取文件名
String entryFileName = archiveEntry.getName();
//构造解压出来的文件存放路径
String entryFilePath = saveFileDir + entryFileName;
byte[] content = new byte[(int) archiveEntry.getSize()];
zais.read(content);
OutputStream os = null;
try {
//把解压出来的文件写到指定路径
File entryFile = new File(entryFilePath);
os = new BufferedOutputStream(new FileOutputStream(entryFile));
os.write(content);
}catch(IOException e) {
throw new IOException(e);
}finally {
if(os != null) {
os.flush();
os.close();
}
}
}
}catch(Exception e) {
throw new RuntimeException(e);
}finally {
try {
if(zais != null) {
zais.close();
}
if(is != null) {
is.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
} /**
* 判断文件名是否以.zip为后缀
* @param fileName 需要判断的文件名
* @return 是zip文件返回true,否则返回false
*/
public static boolean isEndsWithZip(String fileName) {
boolean flag = false;
if(fileName != null && !"".equals(fileName.trim())) {
if(fileName.endsWith(".ZIP")||fileName.endsWith(".zip")){
flag = true;
}
}
return flag;
} }

Struts2 多文件下载的更多相关文章

  1. 关于Struts2的文件下载

    首先先来说下关于文件下载的原理: 服务端为客户端提供了一个下载服务,所以服务端需要一个输出流(把客户请求下载的文件输出),相对于服务端来说,客户端需要下载接收一个文件,所以它需要一个输入流(接收文件) ...

  2. 基于 Struts2 的文件下载

    介于上篇我们讲述了基于 Struts2 的单文件和多文件上传,这篇我们来聊一聊基于 Struts2 的文件下载. 1.导 jar 包 commons-io-2.0.1.jar struts2-core ...

  3. Struts2笔记--文件下载

    Struts2提供了stream结果类型,该结果类型是专门用于支持文件下载功能的.配置stream类型的结果需要指定以下4个属性. contentType:指定被下载文件的文件类型 inputName ...

  4. Struts2实现文件下载

    实现文件下载: 1.导包:commons-fileload-xx.jar commons-io-xx.jar 2.jsp页面: <s:iterator value="#session. ...

  5. Struts2中文件下载

    在struts.xml中配置如下 <action name="download" class="cn.itcast.domain.User" method ...

  6. struts2 实现文件下载方法汇总

    http://pengranxiang.iteye.com/blog/259401 一.通过struts2提供的下载机制下载文件: 项目名为 struts2hello ,所使用的开发环境是MyEcli ...

  7. 使用struts2进行文件下载以及下载权限控制的例子

    本测试有两个模块,一个是文件上上传,一个是文件下载,文件下载的时候会检查是否足有权限,如果没有,就会转发到登录页面,如果有权限,就会直接启动下载程序,给浏览器一个输出流. 下面直接上我的代码: 登录表 ...

  8. java之struts2之文件下载

    1.在实际应用开发中,文件下载功能也非常常见. 2.最简单的文件下载方式是通过超链接来进行文件下载: <body> <a href="download/s.txt" ...

  9. java struts2 的 文件下载

    jsp: <%@ page language="java" contentType="text/html; charset=UTF-8" pageEnco ...

随机推荐

  1. redis.conf 配置详解

    # Redis 配置文件 # 当配置中需要配置内存大小时,可以使用 1k, 5GB, 4M 等类似的格式,其转换方式如下(不区分大小写) # # 1k => 1000 bytes # 1kb = ...

  2. 谈谈以下关键字的作用auto static register const volatile extern

    (1)auto 这个这个关键字用于声明变量的生存期为自动,即将不在任何类.结构.枚举.联合和函数中定义的变量视为全局变量,而在函数中定义的变量视为局部变量.这个关键字不怎么多写,因为所有的变量默认就是 ...

  3. ZOJ3228 - Searching the String(AC自动机)

    题目大意 给定一个文本串,接下来有n个模式串,每次查询模式串出现的次数,查询分两种,可重叠和不可重叠 题解 第一次是把AC自动机构造好,跑n次,统计出每个模式串出现的次数,交上去果断TLE...后来想 ...

  4. 【ACM/ICPC2013】POJ基础图论题简析(一)

    前言:昨天contest4的惨败经历让我懂得要想在ACM领域拿到好成绩,必须要真正的下苦功夫,不能再浪了!暑假还有一半,还有时间!今天找了POJ的分类题库,做了简单题目类型中的图论专题,还剩下二分图和 ...

  5. CF_402B 想法题

    题目链接:http://codeforces.com/problemset/problem/402/B /**算法分析: 题意太大意,positive没注意这个问题 考察等差数列,由An=A1+(n- ...

  6. Codeforces Round #313 (Div. 2) D.Equivalent Strings (字符串)

    感觉题意不太好懂 = =# 给两个字符串 问是否等价等价的定义(满足其中一个条件):1.两个字符串相等 2.字符串均分成两个子串,子串分别等价 因为超时加了ok函数剪枝,93ms过的. #includ ...

  7. 版本控制Subversion TortoiseSVN apache VisualSVN笔记(转载)

    转载于http://blog.sina.com.cn/s/blog_6b94d5680101m7ah.html Subversion(简称svn)是近年来崛起的版本管理软件,是cvs的接班人.目前,绝 ...

  8. java web知识点总结

    创建与销毁 ServletContext HttpRequest HttpSession 1.ServletContext 创建:启动服务器时就创建,服务为每个web应用创建该项目的ServleCon ...

  9. SecureCRT学习之道:SecureCRT经常使用快捷键设置与字体设置方法

    1:假设不想每次登陆都输入password,能够在你打开的session里邮件session option->login action 选中automate logon 双击ogin 和assw ...

  10. dmesg 程序崩溃调试

    [root@localhost log]# cat -n /root/xx.c #include <stdio.h> void func(char *p) { *p = 'p'; } in ...