当前位置: 移动技术网 > IT编程>开发语言>Java > java后台批量下载文件并压缩成zip下载的方法

java后台批量下载文件并压缩成zip下载的方法

2019年07月19日  | 移动技术网IT编程  | 我要评论

葬尸经,网站忧化,陈华女士回忆录

本文实例为大家分享了java后台批量下载文件并压缩成zip下载的具体代码,供大家参考,具体内容如下

因项目需要,将服务器上的图片文件压缩打包zip,下载到本地桌面。

首先,前端js:

function doquerypic() {
 var picsdate = $("#picsdate").val();
 var picedate = $("#picedate").val();
 var picinst = $("#pic_inst").combotree("getvalue");
 var svrcode = $("#pic_svr_code").val();
 var picstime = $("#pic_stime").val();
 var picetime = $("#pic_etime").val();
 if (svrcode == null) {
 $.messager.alert('提示', "请输入交易查询代号");
 return;
 }else{
 $.ajax({
 type: "post",
 url: 'querypic.translog.action',
 data: {f_brno:picinst,f_sdate:picsdate,f_edate:picedate,f_svr_code:svrcode,f_stime:picstime,f_etime:picetime},
 success: function(rcdata){
 if(rcdata.success){
 var rows = rcdata.picinfo;
 var detailhtml = "<table class='my-form-table' cellpadding='0' cellspacing='0' width='90%' align='center'><thead><tr><th style='width: 5%;text-align: center'><input type='checkbox' onclick='swapcheck()' />全选</th><th style='width: 10%;text-align: center'>日期</th><th style='width: 10%;text-align: center'>有无影像</th><th style='width: 23%;text-align: center'>交易名称</th><th style='width: 10%;text-align: center'>交易状态</th><th style='width: 12%;text-align: center'>设备编号</th><th style='width: 10%;text-align: center'>交易代号</th><th style='width: 10%;text-align: center'>所属机构</th><th style='width: 10%;text-align: center'>交易时间</th></tr></thead><tbody>";
  for(var i = 0;i < rows.length;i++){
 detailhtml = detailhtml + "<tr><td align='center'><input type='checkbox' name='pictureid' value='"+ rows[i].f_date + rows[i].f_ics_batch +"' /></td><td>" + rows[i].f_date + "</td><td>" + rows[i].ishasimg + "</td><td>" + rows[i].f_tx_name + "</td><td>" + rows[i].f_stus + "</td><td>" + rows[i].f_dev_id + "</td><td>" + rows[i].f_svr_code + "</td><td>" + rows[i].f_brno + "</td><td>" + rows[i].f_time + "</td></tr>"; 
 }
  detailhtml = detailhtml + "</tbody></table>";
 document.getelementbyid("details").innerhtml = detailhtml;
  
 }else{
 $.messager.alert('提示',rcdata.errmsg);
 }
 
 },
 error:function(){
 alert("查询失败!");
 }
 });
 }
 
}

以上代码是查询到相关数据后,显示在界面上,然后按客户需要可以自己选择下载哪几条数据保存。

附上checkbox全选/取消全选js代码

//checkbox 全选/取消全选
var ischeckall = false;
function swapcheck() {
 if (ischeckall) {
 $("input[type='checkbox']").each(function() {
 this.checked = false;
 });
 ischeckall = false;
 } else {
 $("input[type='checkbox']").each(function() {
 this.checked = true;
 });
 ischeckall = true;
 }
}

下面代码是用来后台交互的,提示一下,下载文件都不要用ajax来送数据,我之前就是ajax做的,一直没法下载,困扰了一整天后来才发现的,注释部分就是ajax代码,大家作为参考可以看一下:

function downloadpic() {
 var arr = new array(); 
 var picids = document.getelementsbyname("pictureid"); 
 for (i = 0; i < picids.length; i++) {  
 if (picids[i].checked) {  
 arr.push(picids[i].value);  
 } 
 }
 
 if (arr.length <= 0 ) {
 $.messager.alert('提示', "无下载内容!");
 return;
 }else{
 $('#formpic').attr('action','downloadpic.translog.action');
 $("#formpic").form('submit',{
 onsubmit:function(){
 
 },
 success:function(data){
 $.messager.alert('提示','图片下载成功','info');
 }
 });

 /**
 *$.ajax({
 type: "post",
 url: 'downloadpic.translog.action',
 data: {picturelist:json.stringify(arr)},
 success: function(rcdata){
 if(rcdata.success){
 $.messager.show({
 title : '成功',
 msg : rcdata.errmsg
 }); 
 }else{
 $.messager.alert('提示',rcdata.errmsg);
 }
 
 },
 error:function(){
 alert("查询失败!");
 }
 }); */
 }
 
}

接下来是后台交互,首先是controller控制层:

/**
 * 图片批量下载
 * @param request
 * @param response
 * @return
 * @throws ioexception 
 */
 public void downloadpic(httpservletrequest request,httpservletresponse response) throws ioexception{
 //map<string, object> params = getparameters(request);
 string[] pictureids = request.getparametervalues("pictureid");
 authentication au=getauthentication(request);
 service.downloadpic(pictureids, au, request, response);
 return ;
 }

service层:

public void downloadpic(string[] params,authentication au,httpservletrequest request,httpservletresponse response) throws ioexception {
 
 //压缩文件初始设置
 string path=system.getproperty("ics.webapp.root");//这个是服务器路径地址,request.getsession().getservletcontext().getrealpath() 也一样能
 string filezip = au.getusername()+"-"+au.getattribute("f_brno")+ "pictures.zip";
 string filepath = path+"\\" + filezip;//之后用来生成zip文件
 
 //filepatharr为根据前台传过来的信息,通过数据库查询所得出的pdf文件路径集合(具体到后缀)
 list<map<string, object>> filenamearr = new arraylist<map<string,object>>();
 //jsonarray jsons = jsonarray.fromobject(params.get("picturelist"));
 /**
 *list<string> pictureids = new arraylist<string>();
 for(object obj:jsons){
 pictureids.add(obj.tostring());
 }
 */
 for (int i = 0; i < params.length; i++) {
 map<string, object> spemap = new hashmap<string, object>();
 spemap.put("f_date", params[i].substring(0, 8));
 spemap.put("f_ics_batch", params[i].substring(8));
 list<map<string, object>> reclists=dao.queryloginfo(spemap);
 for (int j = 0; j < reclists.size(); j++) {
 filenamearr.add(reclists.get(j));
 }
 }
 
 //需要压缩的文件--包括文件地址和文件名
 //string[] pathtytytyt ={"d:\\13.jpg","d:\\1212.jpg"};
 // 要生成的压缩文件地址和文件名称
 //string despath = "d:\\downloads\\new.zip";
 file zipfile = new file(filepath);
 zipoutputstream zipstream = null;
 fileinputstream zipsource = null;
 bufferedinputstream bufferstream = null;
 try {
 //构造最终压缩包的输出流
 zipstream = new zipoutputstream(new fileoutputstream(zipfile));
 for(int i =0;i<filenamearr.size();i++){
 file file = new file((string) filenamearr.get(i).get("f_filename"));
 //file file = new file(pathtytytyt[i]);
 //将需要压缩的文件格式化为输入流
 zipsource = new fileinputstream(file);
 //压缩条目不是具体独立的文件,而是压缩包文件列表中的列表项,称为条目,就像索引一样
 //这里的name就是文件名,文件名和之前的重复就会导致文件被覆盖,在这用i加文件名进行单一文件识别
 zipentry zipentry = new zipentry(i+file.getname());
 //定位该压缩条目位置,开始写入文件到压缩包中
 zipstream.putnextentry(zipentry);
 //输入缓冲流
 bufferstream = new bufferedinputstream(zipsource, 1024 * 10);
 int read = 0;
 //创建读写缓冲区
 byte[] buf = new byte[1024 * 10];
 while((read = bufferstream.read(buf, 0, 1024 * 10)) != -1)
 {
 zipstream.write(buf, 0, read);
 }
 }
 
 } catch (exception e) {
 e.printstacktrace();
 } finally {
 //关闭流
 try {
  if(null != bufferstream) bufferstream.close();
  if(null != zipstream) zipstream.close();
  if(null != zipsource) zipsource.close();
 } catch (ioexception e) {
  e.printstacktrace();
 }
 }
 
 /**
 * 写流文件到前端浏览器
 servletoutputstream os = response.getoutputstream();
 response.setcontenttype("application/x-octet-stream");
 response.setcontentlength((int) zipfile.length());
 response.addheader("content-disposition", "attachment;filename=" + urlencoder.encode(filezip, "utf-8"));
 bufferedinputstream bis = null;
 bufferedoutputstream bos = null;
 try {
 bis = new bufferedinputstream(new fileinputstream(filepath));
 bos = new bufferedoutputstream(os);
 byte[] buff = new byte[2048];
 int bytesread;
 while (-1 != (bytesread = bis.read(buff, 0, buff.length))) {
 bos.write(buff, 0, bytesread);
 }
 os.flush();
 os.close();
 } catch (ioexception e) {
 throw e;
 } finally {
 if (bis != null)
 bis.close();
 if (bos != null)
 bos.close();
 file obj = new file(filepath);
 if (obj.exists()) {
 obj.delete();//删除服务器本地产生的临时压缩文件
 }
 }*/
 
 
 //进行浏览器下载 
 //获得浏览器代理信息
 final string useragent = request.getheader("user-agent");
 //判断浏览器代理并分别设置响应给浏览器的编码格式
 string finalfilename = null;
 if(stringutils.contains(useragent, "msie")||stringutils.contains(useragent,"trident")){//ie浏览器
 finalfilename = urlencoder.encode(filezip,"utf-8");
 system.out.println("ie浏览器");
 }else if(stringutils.contains(useragent, "mozilla")){//google,火狐浏览器
 finalfilename = urlencoder.encode(filezip,"utf-8");
 }else{
 finalfilename = urlencoder.encode(filezip,"utf-8");//其他浏览器
 }
 response.setcontenttype("application/x-octet-stream");//告知浏览器下载文件,而不是直接打开,浏览器默认为打开
 response.setheader("content-disposition" ,"attachment;filename=" +finalfilename);//下载文件的名称
 
 servletoutputstream servletoutputstream=response.getoutputstream();
 dataoutputstream temps = new dataoutputstream(servletoutputstream);
 
 datainputstream in = new datainputstream(new fileinputstream(filepath));//浏览器下载文件的路径
 byte[] b = new byte[2048];
 file reportzip=new file(filepath);//之后用来删除临时压缩文件
 try {
 while ((in.read(b)) != -1) {
 temps.write(b);
 }
 temps.flush();
 } catch (exception e) {
 e.printstacktrace();
 optlogsvc.savelog(au.getusername(), au.getattribute("f_brno"), au.getattribute("f_lstip"),
 toptlogservice.type_mr, "", au.getusername() + "批量下载图片"+filezip+"失败!");
 }finally{
 if(temps!=null) temps.close();
 if(in!=null) in.close();
 if(reportzip!=null) reportzip.delete();//删除服务器本地产生的临时压缩文件
 servletoutputstream.close();
 }
 /**
 *if (picinfollist.size() > 0) {
 rc.put("success", true);
 rc.put("picinfo", picinfollist);
 optlogsvc.savelog(au.getusername(), au.getattribute("f_brno"), au.getattribute("f_lstip"),
 toptlogservice.type_mr, "", au.getusername() + "查询批量下载"+params.get("f_svr_code")+"成功!");
 } else {
 rc.put("success", false);
 rc.put("errmsg", "test info");
 optlogsvc.savelog(au.getusername(), au.getattribute("f_brno"), au.getattribute("f_lstip"),
 toptlogservice.type_mr, "", au.getusername() + "查询批量下载"+params.get("f_svr_code")+"失败!");
 }*/
 optlogsvc.savelog(au.getusername(), au.getattribute("f_brno"), au.getattribute("f_lstip"),
 toptlogservice.type_mr, "", au.getusername() + "批量下载图片"+filezip+"成功!");
 return ;
 }

里面夹杂了json数组转格式问题,前端json传过来的如果是json.stringify格式化的,到后台就得用这种方式进行解析。

本人排版能力不咋样,大家将就看看,那边判断浏览器的也是网上抄的,结果发现根本没有用,无法识别中文,最后妥协了还是使用英文做文件名。如果有碰到中文乱码的,大家可以百度再搜搜,有其他人写过类似文章,我没精力研究了。

这个是压缩服务器上本身存在的文件方法,之前百度相关文章还看到过获取网络图片并压缩下载的,有点意思。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网