本篇文章给大家分享的是有关JavaWeb项目中怎么实现一个文件压缩下载功能,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
实现思路有两种:
一是将所有文件先打包压缩为一个文件,然后下载这个压缩包,
二是一边压缩一边下载,将多个文件逐一写入到压缩文件中。
代码实现:
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项目中怎么实现一个文件压缩下载功能,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。