java选中文件批量下载_Java实现批量下载选中文件功能

Java实现批量下载选中文件功能

发布于 2020-3-28|

复制链接

摘记: 1.在action中定义变量

```java

private List downLoadPaths = new ArrayList();//存储选中文件的下载地址

private OutputStream res;

private ZipOutputStream zos ..

1.在action中定义变量

```java

private List downLoadPaths = new ArrayList();//存储选中文件的下载地址

private OutputStream res;

private ZipOutputStream zos;

private String outPath;

private String lessionIdStr;// 选中文件ID拼接的字符串

private String fileName; //浏览器下载弹出框中显示的文件名

```

分别给出get和set方法2.  主方法

```java

/**

* 下载多个文件:压缩成zip

*

* @return

* @throws Exception

*/

public String downLoadLessionsZip() {

downLoadPaths.clear();

String firstFileName = "";// 第一个文件的文件名

List fileVos = new LinkedList();

if (StringUtils.isNotEmpty(lessionIdStr)) {

int end = lessionIdStr.lastIndexOf(",");

if (end > 0) {

if (end == lessionIdStr.length() - 1) {

lessionIdStr = lessionIdStr.substring(0, end);

}

String[] ids = lessionIdStr.split(",");

for (int i = 0; i fileVos) {

byte[] buf = new byte[8192];

int len;

for (DownLoadFileVo fileVo : fileVos) {

File file = new File(fileVo.getFileSavePath());

if (!file.isFile())

continue;

ZipEntry ze = new ZipEntry(fileVo.getFileName()

+ fileVo.getFileSavePath().substring(

fileVo.getFileSavePath().lastIndexOf(".")));

try {

zos.putNextEntry(ze);

BufferedInputStream bis = new BufferedInputStream(

new FileInputStream(file));

while ((len = bis.read(buf)) > 0) {

zos.write(buf, 0, len);

}

bis.close();

zos.closeEntry();

} catch (IOException e) {

e.printStackTrace();

}

}

}

// 预处理

public void preProcess(String firseFileName) {

String zipName = "【批量下载】" + firseFileName + "等.zip";

String filename = "";

try {

filename = new String(zipName.getBytes("GBK"), "8859_1");

} catch (UnsupportedEncodingException e1) {

e1.printStackTrace();

}

this.fileName = filename;

HttpServletResponse response = ServletActionContext.getResponse();

try {

res = response.getOutputStream();

// 清空输出流(在迅雷下载不会出现一长窜)

response.reset();

// 设定输出文件头

response.setHeader("Content-Disposition", "attachment;fileName="

+ filename);

response.setContentType("application/zip");

zos = new ZipOutputStream(res);

} catch (IOException e) {

e.printStackTrace();

}

}

// 后处理

public void afterProcess() {

try {

if (zos != null) {

zos.close();

}

if (res != null) {

res.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

```

3. 在struts.xml中配置

```java

//class值为bean.xml中配置的bean

204//表示响应执行成功,但没有数据返回,浏览器不用刷新,不用导向新页面

```

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值