1. Download the batch file
Recent projects have a demand for bulk users download the pdf file, the following recording solution I realized.
Front-end code (based vue):
//批量下载用户选中的一些质量证明书 downloadSomeQualityPaper() { let trs = document.getElementById("check-state").getElementsByTagName("tr"); let inputs=document.getElementById("check-state").getElementsByTagName("input"); let lotnoid=""; for (let i = 1; i <inputs.length ; i++) { if(inputs[i].checked){ let tds=trs[i].getElementsByTagName("td"); lotnoid=lotnoid+tds[2].innerText+","; } } console.log(lotnoid); this.form.lotnoid=lotnoid; aozhan.http.post("/user/downloadSomeQualityPaper", aozhan.stringify(this.form),{responseType: 'blob'}) .then(resp => { if (resp.status === 200) { const link = document.createElement('a'); let blob = new Blob([resp.data],{type: 'application/zip'}); link.style.display = 'none'; link.href = URL.createObjectURL(blob); link.setAttribute('download', '质保书.zip'); document.body.appendChild(link); link.click(); document.body.removeChild(link); } }) .catch(() => this.msg = '') },
Back-end code (based springboot):
/ ** * Features: According to product lot number to download a collection of batch quality certificate * @param Request HTTP Request request * @param the Response HTTP response to the Response * @param lotnoid batch collection * / @PostMapping ( "downloadSomeQualityPaper" ) public ResponseEntity <Void> downloadSomeQualityPaper (the HttpServletRequest Request, Response the HttpServletResponse, String lotnoid) { // set 1 defines the path and file name stored List <String> = names new new the ArrayList <> (); List <String> paths = new new the ArrayList <> (); String [] lotnoids= lotnoid.split(","); for (int i = 0; i <lotnoids.length ; i++) { QualityPaperMessage qualityPaperMessage=new QualityPaperMessage(); qualityPaperMessage.setLotno(lotnoids[i]); List<QualityPaperMessage> qualityPaperMessageList = qualityPaperMessageMapper.select(qualityPaperMessage); QualityPaperMessage queryResult=null; if(qualityPaperMessageList.size()>0){ queryResult=qualityPaperMessageList.get(qualityPaperMessageList.size()-1); Path String = queryResult.getResourcelocation (); String filename = queryResult.getLotno () +. "PDF" ; Names.Add (filename); paths.add (path); } } // store zip file directory on the server String directory =: "D \\ \\ ziptemp Repository" ; File directoryFile = new new ; File (Directory) IF (!! directoryFile.isDirectory () && directoryFile.exists ()) { directoryFile.mkdirs (); } // set the final output zip file directory + filename SimpleDateFormat formatter =new new SimpleDateFormat ( "yyyy Year MM Month dd Day HH mm ss a time" ); String zipFileName = formatter.format ( new new a Date ()) + "warranty book .zip" ; String strZipPath = Directory + "\\" + zipFileName; zipStream the ZipOutputStream = null ; the FileInputStream zipSource = null ; BufferedInputStream bufferStream = null ; File ZipFile = new new File (strZipPath); the try { // construct the final compressed output stream zipStream = new newThe ZipOutputStream ( new new a FileOutputStream (ZipFile)); for ( int I = 0; I <paths.size (); I ++ ) { // decode the real path and file name Get String realFileName = names.get (I); String realFilePath = Paths .get (i); file file = new new file (realFilePath); // TODO: no operation for a file does not exist, post optimization. IF (File.Exists ()) { zipSource = new new the FileInputStream (File); // the file needs to be compressed formatted input stream / ** * Compression is not independent of the specific file entry, but the list of items compressed package list file, called entries, like the index name here is the file name, * file name and duplicate files will be overwritten lead before * / the ZipEntry for the ZipEntry = new new the ZipEntry (realFileName); // the name of the directory file compression zipStream.putNextEntry (ZipEntry); // locate the position of the compressed entry, starts writing the file to the compressed package bufferStream = new new BufferedInputStream (zipSource, 1024 * 10 ); int Read = 0 ; byte [] = buf new new byte [1024 * 10 ]; the 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.flush(); zipStream.close (); } IF ( null ! = zipSource) zipSource.close (); } the catch (IOException E) { e.printStackTrace (); } } // determines whether there is a compressed file system: true- to the archive stream output by deleting the compressed file to the client false- untreated IF (zipFile.exists ()) { DownloadUtil.downloadFile (strZipPath, zipFileName, Response, Request); // downImg (Response, zipFileName, strZipPath); ZipFile. Delete (); } return new new ResponseEntity <> (HttpStatus.OK); }
Download tools:
Package lucky.aozhan.user.utils; Import the javax.servlet.http.HttpServletRequest; Import javax.servlet.http.HttpServletResponse; Import the java.io. * ; Import java.net.URLEncoder; / ** * * The contents of the file in response to to the browser * / public class DownloadUtil { // character encoding format Private static String charsetCode = "UTF-. 8" ; / ** * content type of file * / Private static String getFileContentType (String name) { String Result = "" ; fileType String = name.toLowerCase(); if (fileType.endsWith(".png")) { result = "image/png"; } else if (fileType.endsWith(".gif")) { result = "image/gif"; } else if (fileType.endsWith(".jpg") || fileType.endsWith(".jpeg")) { result = "image/jpeg"; } else if(fileType.endsWith(".svg")){ result = "image/svg+xml"; }else if (fileType.endsWith(".doc")) { result = "application/msword"; } else if (fileType.endsWith(".xls")) { result = "application/x-excel"; } else if (fileType.endsWith(".zip")) { result = "application/zip"; } else if (fileType.endsWith(".pdf")) { result = "application/pdf"; } else if (fileType.endsWith(".xlsx")) { Result = "file application / vnd.ms-Excel" ; } the else { Result = "file application / OCTET-Stream" ; } return Result; } / ** * download file * @param where path file * @param fileName Custom Download file name * @param RESP HTTP response * @param REQ HTTP request * / public static void the downloadFile (path String, String fileName, the HttpServletResponse RESP, the HttpServletRequest REQ) { the try { File File = new new File(path); /** * 中文乱码解决 */ String type = req.getHeader("User-Agent").toLowerCase(); if(type.indexOf("firefox")>0 || type.indexOf("chrome")>0){ /** * 谷歌或火狐 */ fileName = new String(fileName.getBytes(charsetCode), "iso8859-1"); }else{ /** * IE */ fileName =The URLEncoder.encode (fileName, charsetCode); } // set the response header information resp.setHeader ( "Content-Disposition", "Attachment; filename =" + fileName); // set the response content type String contentType = getFileContentType ( fileName) + "; charset =" + charsetCode; resp.setContentType (contentType); System.out.println ( "contentType:" + contentType); // set the length of the response content // resp.setContentLength ((int) File. length ()); resp.setHeader ( "the Content-the length" , String.valueOf (file.length ())); // output the outStream ( the FileInputStream (File), resp.getOutputStream ()); } the catch (Exception E) { System.out.println ( "downloadFile performed abnormality occurs:" + e.getMessage ()); } } / ** * based output byte array * / Private static void the outStream (the InputStream IS, the OutputStream OS) { the try { byte [] Buffer = new new byte [1024 ]; int length = -1 ; the while ((length = is.read (Buffer))! = -1 ) { new new os.write (Buffer, 0, length); os.flush(); } } catch (Exception e) { System.out.println("执行 outStream 发生了异常:" + e.getMessage()); } finally { try { os.close(); } catch (IOException e) { } try { is.close(); } catch (IOException e) { } } } }