欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2021年10月19日 09:33:53   作者:blackalone  
這篇文章主要為大家詳細介紹了java后臺批量下載文件并壓縮成zip下載的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下

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

因項目需要,將服務器上的圖片文件壓縮打包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'>設備編號</th><th style='width: 10%;text-align: center'>交易代號</th><th style='width: 10%;text-align: center'>所屬機構(gòu)</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("查詢失敗!");
 }
 });
 }
 
}

以上代碼是查詢到相關(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 {
 
 //壓縮文件初始設置
 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為根據(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);
 //壓縮條目不是具體獨立的文件,而是壓縮包文件列表中的列表項,稱為條目,就像索引一樣
 //這里的name就是文件名,文件名和之前的重復就會導致文件被覆蓋,在這用i加文件名進行單一文件識別
 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();//刪除服務器本地產(chǎn)生的臨時壓縮文件
 }
 }*/
 
 
 //進行瀏覽器下載 
 //獲得瀏覽器代理信息
 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();//刪除服務器本地產(chǎn)生的臨時壓縮文件
 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格式化的,到后臺就得用這種方式進行解析。

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

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

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java文件操作之按行讀取文件和遍歷目錄的方法

    Java文件操作之按行讀取文件和遍歷目錄的方法

    這篇文章主要介紹了Java文件操作之按行讀取文件和遞歸遍歷目錄的方法,遍歷目錄文中分別舉了遞歸和非遞歸的例子,需要的朋友可以參考下
    2016-03-03
  • java中File類應用遍歷文件夾下所有文件

    java中File類應用遍歷文件夾下所有文件

    這篇文章主要為大家詳細介紹了java中File類應用遍歷文件夾下所有文件,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-08-08
  • spring后置通知@AfterReturning的使用

    spring后置通知@AfterReturning的使用

    這篇文章主要介紹了spring后置通知@AfterReturning的使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-05-05
  • java 中 poi解析Excel文件版本問題解決辦法

    java 中 poi解析Excel文件版本問題解決辦法

    這篇文章主要介紹了java 中 poi解析Excel文件版本問題解決辦法的相關(guān)資料,需要的朋友可以參考下
    2017-08-08
  • protobuf與json轉(zhuǎn)換小結(jié)

    protobuf與json轉(zhuǎn)換小結(jié)

    protobuf對象不能直接使用jsonlib去轉(zhuǎn),因為protobuf生成的對象的get方法返回的類型有byte[],而只有String類型可以作為json的key,protobuf提供方法進行轉(zhuǎn)換
    2017-07-07
  • 如何使用Guava Cache做緩存

    如何使用Guava Cache做緩存

    Cache在ConcurrentHashMap的基礎(chǔ)上提供了自動加載數(shù)據(jù)、清除數(shù)據(jù)、get-if-absend-compute的功能,本文給大家介紹如何使用Guava Cache做緩存,感興趣的朋友一起看看吧
    2023-11-11
  • Java Servlet線程中AsyncContext異步處理Http請求

    Java Servlet線程中AsyncContext異步處理Http請求

    這篇文章主要介紹了Java Servlet線程中AsyncContext異步處理Http請求及在業(yè)務中應用,AsyncContext是Servlet 3.0使Servlet 線程不再需要一直阻塞,直到業(yè)務處理完畢才能再輸出響應,最后才結(jié)束該Servlet線程
    2023-03-03
  • 淺談SpringBoot 中關(guān)于自定義異常處理的套路

    淺談SpringBoot 中關(guān)于自定義異常處理的套路

    這篇文章主要介紹了淺談SpringBoot 中關(guān)于自定義異常處理的套路,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-04-04
  • 全面了解JAVA_BaseDAO數(shù)據(jù)處理類

    全面了解JAVA_BaseDAO數(shù)據(jù)處理類

    下面小編就為大家?guī)硪黄媪私釰AVA_BaseDAO數(shù)據(jù)處理類。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-07-07
  • RestTemplate的DELETE及PUT等請求方法使用精講

    RestTemplate的DELETE及PUT等請求方法使用精講

    這篇文章主要為大家介紹了RestTemplate的DELETE及PUT等請求方法的使用精講,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步
    2022-03-03

最新評論