您的位置:首页 > 编程语言 > Java开发

JavaWeb 实现多个文件压缩下载功能

2017-07-31 14:21 1206 查看

文件下载时,我们可能需要一次下载多个文件。批量下载文件时,需要将多个文件打包为zip,然后再下载。

实现思路有两种:

一是将所有文件先打包压缩为一个文件,然后下载这个压缩包,

二是一边压缩一边下载,将多个文件逐一写入到压缩文件中。我这里实现了边压缩边下载。

下载样式:

点击下载按钮,会弹出下载框:

下载后就有一个包含刚刚选中的两个文件:


代码实现:

FileBean

public class FileBean implements Serializable {
private Integer fileId;// 主键
private String filePath;// 文件保存路径
private String fileName;// 文件保存名称
public FileBean() {
}
public Integer getFileId() {
return fileId;
}
public void setFileId(Integer fileId) {
this.fileId = fileId;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}

控制层:

@RequestMapping(value = "/download", method = RequestMethod.GET)
public String download(String id, HttpServletRequest request,
HttpServletResponse response) throws IOException {
String str = "";
if (id != null && id.length() != 0) {
int index = id.indexOf("=");
str = id.substring(index + 1);
String[] ids = str.split(",");
ArrayList<FileBean> fileList = new ArrayList<FileBean>();
for (int i = 0; i < ids.length; i++) {// 根据id查找genericFileUpload,得到文件路径以及文件名
GenericFileUpload genericFileUpload = new GenericFileUpload();
genericFileUpload = genericFileUploadService.find(Long.parseLong(ids[i]));
FileBean file = new FileBean();
file.setFileName(genericFileUpload.getFileName());
file.setFilePath(genericFileUpload.getFilePath());
fileList.add(file);
}
//设置压缩包的名字
//解决不同浏览器压缩包名字含有中文时乱码的问题
String zipName = "download.zip";
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment; filename="+ zipName);
//设置压缩流:直接写入response,实现边压缩边下载
ZipOutputStream zipos =null;
try{
zipos=new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
zipos.setMethod(ZipOutputStream.DEFLATED);//设置压缩方法
}catch(Exception e){
e.printStackTrace();
}
DataOutputStream os=null;
//循环将文件写入压缩流
for(int i=0;i<fileList.size();i++){
String filePath=fileList.get(i).getFilePath();
String fileName=fileList.get(i).getFileName();
File file=new File(filePath+"/"+fileName);//要下载文件的路径
try{
//添加ZipEntry,并ZipEntry中写入文件流
//这里,加上i是防止要下载的文件有重名的导致下载失败
zipos.putNextEntry(new ZipEntry(i+fileName));
os=new DataOutputStream(zipos);
InputStream is=new FileInputStream(file);
byte[] b = new byte[100];
int length = 0;
while((length = is.read(b))!= -1){
os.write(b, 0, length);
}
is.close();
zipos.closeEntry();
}catch(Exception e){
e.printStackTrace();
}
}
//关闭流
try {
os.flush();
os.close();
zipos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return "redirect:list.jhtml";
}

总结

以上所述是小编给大家介绍的JavaWeb 实现多个文件压缩下载功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

您可能感兴趣的文章:

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