JavaWeb实现多个⽂件压缩下载功能⽂件下载时,我们可能需要⼀次下载多个⽂件。批量下载⽂件时,需要将多个⽂件打包为zip,然后再下载。实现思路有两种:
⼀是将所有⽂件先打包压缩为⼀个⽂件,然后下载这个压缩包,
⼆是⼀边压缩⼀边下载,将多个⽂件逐⼀写⼊到压缩⽂件中。我这⾥实现了边压缩边下载。
下载样式:
点击下载按钮,会弹出下载框:
下载后就有⼀个包含刚刚选中的两个⽂件:
代码实现:
FileBean
public class FileBean implements Serializable {
private Integer fileId;// 主键web下载官方下载
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.FileName());
file.FilePath());
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 OutputStream()));        zipos.setMethod(ZipOutputStream.DEFLATED);//设置压缩⽅法
}catch(Exception e){
e.printStackTrace();
}
DataOutputStream os=null;
//循环将⽂件写⼊压缩流
for(int i=0;i<fileList.size();i++){
String (i).getFilePath();
String (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 实现多个⽂件压缩下载功能,希望对⼤家有所帮助,如果⼤家有任何疑问请给我留⾔,⼩编会及时回复⼤家的。在此也⾮常感谢⼤家对⽹站的⽀持!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。