This article shares the specific code for java background batch download files and compressing them into zip downloads for your reference. The specific content is as follows
Due to project needs, the image files on the server are compressed and packaged, and downloaded to the local desktop.
First, front-end js:
function doQueryPic() { var picsDate = $("#picsDate").val(); var pianoDate = $("#picDate").val(); var picInst = $("#pic_inst").combotree("getValue"); var svrCode = $("#pic_svr_code").val(); var picsTime = $("#pic_stime").val(); var pianoTime = $("#pic_etime").val(); if (svrCode == null) { $.messager.alert('Hint', "Please enter the transaction query code"); return; }else{ $.ajax({ type: "POST", url: 'queryPic.translog.action', data: {f_brno:picInst,f_sdate:picsDate,f_edate:picDate,f_svr_code:svrCode,f_stime:picsTime,f_etime:picTime}, success: function(rcdata){ if(rcdata.success){ var rows = rcdata.picInfo; var detailsHtml = "<table class='my-form-table' cellpading='0' width='90%' align='center'><tr><th style='width: 5%;text-align: center'><input type='checkbox' onclick='swapCheck()' />Select all</th><th style='width: 10%;text-align: center'>Date</th><th style='width: 10%;text-align: center'>Date</th><th style='width: 10%;text-align: center'>Is there any image</th><th style='width: 23%;text-align: center'>Trading name</th><th style='width: 10%;text-align: center'>Trading status</th><th style='width: 12%;text-align: center'>Device number</th><th style='width: 10%;text-align: center'>Trading code</th><th style='width: 10%;text-align: center'>Affiliated institution</th><th style='width: 10%;text-align: center'>Trading time</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_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('tip',rcdata.errmsg); } }, error:function(){ alert("Query failed!"); } }); } } }The above code is displayed on the interface after querying the relevant data, and then according to the customer's needs, you can choose which pieces of data to download and save.
Attach CheckBox Select All/Cancel Select All js code
//checkbox Select all/cancel Select all 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; }} The following code is used for background interaction. Please remind me that if you download files, don’t use ajax to send data. I did it before and couldn’t download it. I only discovered it after a whole day. The comment part is the ajax code. You can take a look at it as a reference:
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('t prompt', "No download content!"); return; }else{ $('#formPic').attr('action','downLoadPic.translog.action'); $("#formPic").form('submit',{ onSubmit:function(){ }, success:function(data){ $.messager.alert('hint','image download successful','info'); } }); /** *$.ajax({ type: "POST", url: 'downLoadPic.translog.action', data: {pictureList:JSON.stringify(arr)}, success: function(rcdata){ if(rcdata.success){ $.messager.show({ title : 'success', msg : rcdata.errmsg }); }else{ $.messager.alert('Hint',rcdata.errmsg); } }, error:function(){ alert("Query failed!"); } }); */ } } Next is background interaction, first of all, the controller control layer:
/** * Image batch download* @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 layer:
public void downLoadPic(String[] params,Authentication au,HttpServletRequest request,HttpServletResponse response) throws IOException { //Initial setting of the compressed file String path=System.getProperty("ics.webapp.root");//This is the server path address, request.getSession().getServletContext().getRealPath() can also be used String fileZip = au.getUsername()+"-"+au.getAttribute("F_BRNO")+ "Pictures.zip"; String filePath = path+"//" + fileZip;//Then it is used to generate a zip file//filePathArr is the set of pdf file paths obtained through the database query based on the information transmitted from the foreground (specifically to the suffix) 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 < reccists.size(); j++) { fileNameArr.add(recists.get(j)); } } //The file that needs to be compressed-including file address and file name//String[] pathtytytyt ={"D://13.jpg","D://1212.jpg"}; // The compressed file address and file name to be generated//String desPath = "D://DOWNLOADS//new.zip"; File zipFile = new File(filePath); ZipOutputStream zipStream = null; FileInputStream zipSource = null; BufferedInputStream bufferStream = null; try { //Construct the output stream of the final compressed package 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(pathtytyt[i]); //Format the file that needs to be compressed into the input stream zipSource = new FileInputStream(file); //Compressed entries are not specific independent files, but list items in the list of compressed package files, called entries, just like index //The name here is the file name, and the duplication of the file will cause the file to be overwritten. Here, i plus file name is used for single file recognition ZipEntry zipEntry = new ZipEntry(i+file.getName()); //Locate the location of the compressed entry and start writing the file to the compressed package zipStream.putNextEntry(zipEntry); //Input bufferStream = new BufferedInputStream(zipSource, 1024 * 10); int read = 0; //Create read and write buffer 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 { //Close the stream try { if(null != bufferStream) bufferStream.close(); if(null != zipStream) zipStream.close(); if(null != zipSource) zipSource.close(); } catch (IOException e) { e.printStackTrace(); } } /** * Write stream file to the front-end browser 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();//Delete temporary compressed files generated locally by the server} }*/ //Download the browser//Get browser proxy information final String userAgent = request.getHeader("USER-AGENT"); //Judge the browser proxy and set the encoding format that responds to the browser respectively String finalFileName = null; if(StringUtils.contains(userAgent, "MSIE")||StringUtils.contains(userAgent,"Trident")){//IE browser finalFileName = URLEncoder.encode(fileZip,"UTF-8"); System.out.println("IE browser"); }else if(StringUtils.contains(userAgent, "Mozilla")){//google, Firefox browser finalFileName = URLEncoder.encode(fileZip,"UTF-8"); }else{ finalFileName = URLEncoder.encode(fileZip,"UTF-8");//Other browsers} response.setContentType("application/x-octet-stream");//Tell the browser to download the file instead of opening it directly. The browser defaults to open the response.setHeader("Content-Disposition" ,"attachment;filename=" +finalFileName);//The name of the download file ServletOutputStream servletOutputStream=response.getOutputStream(); DataOutputStream temps = new DataOutputStream(servletOutputStream); DataInputStream in = new DataInputStream(new FileInputStream(filePath));//The path to the browser download file byte[] b = new byte[2048]; File reportZip=new File(filePath);//Then it is used to delete the temporary compressed file 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() + "Batch download picture"+fileZip+"failed!"); } finally{ if(temps!=null) temps.close(); if(in!=null) in.close(); if(reportZip!=null) reportZip.delete();//Delete the temporary compressed file generated locally by the server 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() + "Query batch download"+params.get("f_svr_code")+"Success!"); } 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() + "Query batch download"+params.get("f_svr_code")+"Failed!"); }*/ optLogsvc.saveLog(au.getUsername(), au.getAttribute("F_BRNO"), au.getAttribute("F_LSTIP"), TOptlogService.TYPE_MR, "", au.getUsername() + "Batch download picture"+fileZip+"Success!"); return ; }There is a problem with json array conversion format. If the json sent from the front-end json is formatted by json.stringify, it must be parsed in this way when you go to the background.
My layout skills are not good, so let’s take a look. I judged that the browser was copied online, but I found that it was useless and could not recognize Chinese. In the end, I compromised and still used English as the file name. If you encounter Chinese garbled code, you can search again on Baidu. Others have written similar articles, but I don’t have the energy to study them.
This is a method of compressing files that exist on the server. I have also seen Baidu related articles before to obtain network pictures and compress and download them, which is interesting.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.