1 需求分析:
1接收前台传递的ids数组,查询数据库得到本地文件路径
2 创建压缩文件
3 将文件挨个写入压缩文件
4 得到输出流将数据返回,在页面弹出下载框
5 由于使用的是ajax进行下载故将下载过程分成两段
1 用户传递id 查询数据库并生成zip文件
2 向用户返回下载地址,ajax访问该路径完成下载
一 生成压缩文件的方法(R为手写的异常工具类,可去掉直接返回json数据即可)
/**
* 根据用户传递的图片id对查询图片集合
* 包含图片名称和本机图片地址
* 将问价进行打包供用户下载
* @Description: TODO(用一句话描述该文件做什么)
* @author guochao
* @date 2018年4月17日
*
*/
@PostMapping("/user/down/zip.do")
public R downFileZip(@RequestBody long ids[],HttpServletRequest request){
List<DownImgDto> list = imgService.downFileZip(ids);//调用数据库完成数据查找
// 获取项目的临时目录
Object obj =request.getSession().getAttribute(SessionConstract.USER_SESSION); // 获取session中的用户信息
UserEntity user = null;
if(obj!=null){
user = (UserEntity)obj;
}
List<File> fileList = new LinkedList<File>();//暂存文件列表
String path = request.getSession().getServletContext().getRealPath("/uploadFile"); //得到zip文件的生成地址
File fi= new File(path);//构造zip文件存放的目录
if(!fi.exists()){
fi.mkdir();
}
String fileName = user.getName()+Md5Utils.produceImgName(user.getName())+".zip";// 以用户名 和md5根据用户名生成的字符串为名称
if(list!=null && list.size()>0){
for (DownImgDto downImgDto : list) {
File file = new File(downImgDto.getImgUrl()); // 构建本地文件
fileList.add(file); // 将本地文件加入fileList 文件列表
}
}
//构造压缩文件
String zipFileName = path+"/"+fileName;
try {
UserDownZipUtils.downZipManyFile(fileList, zipFileName); // 将文件列表写入压缩文件中
} catch (IOException e) {
e.printStackTrace();
}
String url ="/user/down/zip/url.do";
String realPath = "{\"url\":\""+ url+"\"}"; // 返回下载路径
return R.ok(realPath);
}
二 UserDownZipUtils 压缩工具包
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* 文件打包下载
* 将传递过来的文件列表写入zip文件
* @Description: TODO(用一句话描述该文件做什么)
* @author guochao
* @date 2018年4月17日
*
*/
public class UserDownZipUtils {
public static String downZipManyFile(List<File> fileList,String zipFileName) throws IOException{
BufferedInputStream br = null;//输入流
ZipOutputStream out = null; // 压缩文件输出流
int size =-1;
byte[] buffer = new byte[2048];// 定义缓冲区
if(fileList.size()>0){
out = new ZipOutputStream(new FileOutputStream(zipFileName));
for (int i = 0; i < fileList.size(); i++) {
File f =fileList.get(i);
out.putNextEntry(new ZipEntry(f.getName()));
br = new BufferedInputStream(new FileInputStream(f));
while((size=br.read(buffer))!=-1){
out.write(buffer,0,size);
out.flush();
}
}
if(br!=null){br.close();}
if(out!=null){out.close();}
}
return zipFileName;
}
}
三 经过上面两个步骤文件压缩写入zip已经完成了下面开始进行 提供用户下载的方法编写
/**
* 用户提供下载 路径为上个方法的返回值
* @Description: TODO(用一句话描述该文件做什么)
* @author guochao
* @date 2018年4月17日
*
*/
@RequestMapping("/user/down/zip/url.do")
public void downLoadUrl(HttpServletResponse response,HttpServletRequest request){
Object obj =request.getSession().getAttribute(SessionConstract.USER_SESSION);
UserEntity user = null;
if(obj!=null){
user = (UserEntity)obj;
}
String path = request.getSession().getServletContext().getRealPath("/uploadFile");
File fi= new File(path);
if(!fi.exists()){
fi.mkdir();
}
String fileName = user.getName()+Md5Utils.produceImgName(user.getName())+".zip";
String zipFileName = path+"/"+fileName;
response.setContentType("application/octet-stream");
try {
response.setHeader("Content-disposition", "attachment; filename="
+ new String((fileName).getBytes("utf-8"), "ISO8859-1"));
DataOutputStream temps = new DataOutputStream(response.getOutputStream());
DataInputStream in = new DataInputStream(new FileInputStream(zipFileName));
byte[] b = new byte[2048];
while ((in.read(b)) != -1) {
temps.write(b);
temps.flush();
}
in.close();
temps.close();
} catch (IOException e) {
e.printStackTrace();
}
}
四 :文件zip打包下载已经完成了为了方便大家查看,将js代码也贴一下
$.ajax({
type:'POST',
contentType:'application/json;charset=utf-8',
dataType:'json',
url:"${pageContext.request.contextPath}/user/down/zip.do",
data:JSON.stringify(ids),
success:function(res){
if(res.code == 200){
var jsonstr =res.data;
var a = $.parseJSON( jsonstr );
window.location.href="${pageContext.request.contextPath}/"+a.url;
setTimeout(function(){
location.reload();
}, 2000);
}else{
alert("下载失败,请联系管理员!")
}
}
});