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' οnclick='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格式化的,到后台就得用这种方式进行解析。

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

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

    原文作者:blackalone
    原文地址: https://blog.csdn.net/blackalone/article/details/81033749
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞