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

作者:blackalone 时间:2021-07-24 21:13:11 

本文实例为大家分享了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格式化的,到后台就得用这种方式进行解析。

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

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

来源:https://blog.csdn.net/blackalone/article/details/81033749

标签:java,下载文件,压缩
0
投稿

猜你喜欢

  • Java 在PDF中添加条形码的两种方法

    2023-05-29 19:10:23
  • Springboot整合pagehelper分页功能

    2021-12-14 15:53:48
  • 详谈Java中的Object、T(泛型)、?区别

    2022-06-11 21:13:11
  • Mybatis使用JSONObject接收数据库查询的方法

    2023-01-17 05:10:43
  • Mybatis-Plus之ID自动增长的设置实现

    2022-10-27 00:09:47
  • Java异常处理操作 Throwable、Exception、Error

    2022-02-19 20:56:13
  • 使用纯Java实现一个WebSSH项目的示例代码

    2023-03-11 11:32:20
  • springboot常用注释的讲解

    2023-11-03 02:53:15
  • Java中的守护线程问题

    2023-09-13 11:49:23
  • 深入理解C#中常见的委托

    2022-01-15 07:53:05
  • Spring集成Swagger常见错误及解决办法

    2023-07-10 05:01:17
  • Android实现Banner界面广告图片循环轮播(包括实现手动滑动循环)

    2022-02-06 17:05:35
  • 关于jdk环境变量的配置方式解读

    2023-04-22 14:53:05
  • CountDownLatch和Atomic原子操作类源码解析

    2023-06-07 06:31:52
  • springboot配置aop切面日志打印过程解析

    2022-07-10 13:14:09
  • Spring Boot利用Docker快速部署项目的完整步骤

    2022-03-08 18:52:55
  • C# 通过NI-VISA操作Tektronix TBS 2000B系列示波器的实现步骤

    2023-11-02 01:44:38
  • Spring Batch轻量级批处理框架实战

    2023-01-08 00:24:23
  • JavaWeb使用Cookie模拟实现自动登录功能(不需用户名和密码)

    2021-09-06 00:15:03
  • 详谈signed 关键字

    2022-09-19 13:45:36
  • asp之家 软件编程 m.aspxhome.com