国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發(fā) > Java > 正文

java后臺批量下載文件并壓縮成zip下載的方法

2024-07-14 08:41:34
字體:
供稿:網(wǎng)友

本文實(shí)例為大家分享了java后臺批量下載文件并壓縮成zip下載的具體代碼,供大家參考,具體內(nèi)容如下

因項(xiàng)目需要,將服務(wù)器上的圖片文件壓縮打包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'>交易狀態(tài)</th><th style='width: 12%;text-align: center'>設(shè)備編號</th><th style='width: 10%;text-align: center'>交易代號</th><th style='width: 10%;text-align: center'>所屬機(jī)構(gòu)</th><th style='width: 10%;text-align: center'>交易時(shí)間</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("查詢失敗!"); } }); } }

以上代碼是查詢到相關(guān)數(shù)據(jù)后,顯示在界面上,然后按客戶需要可以自己選擇下載哪幾條數(shù)據(jù)保存。

附上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來送數(shù)據(jù),我之前就是ajax做的,一直沒法下載,困擾了一整天后來才發(fā)現(xiàn)的,注釋部分就是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('提示', "無下載內(nèi)容!"); 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 {  //壓縮文件初始設(shè)置 String path=System.getProperty("ics.webapp.root");//這個是服務(wù)器路徑地址,request.getSession().getServletContext().getRealPath() 也一樣能 String fileZip = au.getUsername()+"-"+au.getAttribute("F_BRNO")+ "Pictures.zip"; String filePath = path+"//" + fileZip;//之后用來生成zip文件  //filePathArr為根據(jù)前臺傳過來的信息,通過數(shù)據(jù)庫查詢所得出的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 { //構(gòu)造最終壓縮包的輸出流 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); //壓縮條目不是具體獨(dú)立的文件,而是壓縮包文件列表中的列表項(xiàng),稱為條目,就像索引一樣 //這里的name就是文件名,文件名和之前的重復(fù)就會導(dǎo)致文件被覆蓋,在這用i加文件名進(jìn)行單一文件識別 ZipEntry zipEntry = new ZipEntry(i+file.getName()); //定位該壓縮條目位置,開始寫入文件到壓縮包中 zipStream.putNextEntry(zipEntry); //輸入緩沖流 bufferStream = new BufferedInputStream(zipSource, 1024 * 10); int read = 0; //創(chuàng)建讀寫緩沖區(qū) 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 { //關(guān)閉流 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();//刪除服務(wù)器本地產(chǎn)生的臨時(shí)壓縮文件 } }*/   //進(jìn)行瀏覽器下載  //獲得瀏覽器代理信息 final String userAgent = request.getHeader("USER-AGENT"); //判斷瀏覽器代理并分別設(shè)置響應(yīng)給瀏覽器的編碼格式 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");//告知瀏覽器下載文件,而不是直接打開,瀏覽器默認(rèn)為打開 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);//之后用來刪除臨時(shí)壓縮文件 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();//刪除服務(wù)器本地產(chǎn)生的臨時(shí)壓縮文件 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數(shù)組轉(zhuǎn)格式問題,前端json傳過來的如果是json.stringify格式化的,到后臺就得用這種方式進(jìn)行解析。

本人排版能力不咋樣,大家將就看看,那邊判斷瀏覽器的也是網(wǎng)上抄的,結(jié)果發(fā)現(xiàn)根本沒有用,無法識別中文,最后妥協(xié)了還是使用英文做文件名。如果有碰到中文亂碼的,大家可以百度再搜搜,有其他人寫過類似文章,我沒精力研究了。

這個是壓縮服務(wù)器上本身存在的文件方法,之前百度相關(guān)文章還看到過獲取網(wǎng)絡(luò)圖片并壓縮下載的,有點(diǎn)意思。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持VeVb武林網(wǎng)。


注:相關(guān)教程知識閱讀請移步到JAVA教程頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 洞口县| 响水县| 寻乌县| 田阳县| 温宿县| 桐庐县| 隆子县| 建瓯市| 垣曲县| 郴州市| 兴宁市| 大渡口区| 宜兰县| 扬州市| 同江市| 抚远县| 奈曼旗| 会昌县| 桑植县| 扶沟县| 莱芜市| 屏东市| 吉安县| 巫山县| 丰原市| 如皋市| 德钦县| 上高县| 金塔县| 湖南省| 沈丘县| 德江县| 萨嘎县| 江孜县| 白朗县| 兴化市| 灵川县| 呼玛县| 栖霞市| 余庆县| 桑日县|