打包下載PDF
阿新 • • 發佈:2018-11-25
/*打包下載*/ @RequestMapping(params = "loadZipPdf") public String loadZipPdf(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("FSDYGCXXID"); if (id == null) { id = dygc_id; } String[] Arr = id.split(","); String ids = ""; for (String s : Arr) { ids += "'"+ s +"',"; } if (Arr.length == 1) { String sql = String.format("select b.FILEPATH,b.FILENAME,a.FSPX,a.FSZH from t_dygcgl_dygcxx_qbs a LEFT JOIN t_sys_files b on a.ID = b.MAINTABLEID WHERE a.FSDYGCXXID = '%s'",id ); List<Map<String, Object>> lst= systemService.findForJdbc(sql) ; List<Map<String, Object>> files = new ArrayList<Map<String, Object>>(); List<Map<String, Object>> name = new ArrayList<Map<String, Object>>(); String root = request.getSession().getServletContext().getRealPath("/"); //File Allfile = new File(request.getSession().getServletContext().getRealPath("/")); if(lst!=null && lst.size()>0){ for(int i =0;i<lst.size();i++){ if (lst.get(i).get("FILEPATH") != null) { Map<String, Object> mp = new HashMap<String, Object>(); Map<String, Object> mps = new HashMap<String, Object>(); String url = lst.get(i).get("FILEPATH").toString(); url = StringUtils.substringBefore(url,"."); String urlname = url + ".pdf"; File file = new File(root+urlname); String names = lst.get(i).get("FILENAME").toString(); String fspx = lst.get(i).get("FSPX").toString(); String fszh = lst.get(i).get("FSZH").toString(); mp.put("PATH", file); mps.put("name", names); mps.put("fspx", fspx); mps.put("fszh", fszh); if(file.exists()){ files.add(mp); name.add(mps); } } } } String sqls = String.format("select fsdygcmc from t_dygcgl_dygcxx where id = '%s'",id ); Map<String, Object> map = systemService.findOneForJdbc(sqls); String fileName = map.get("fsdygcmc").toString() +"_pdf"+ ".zip"; String userAgent = request.getHeader("user-agent"); userAgent = userAgent ==null?"":userAgent.toLowerCase(); String names = fileName; try { if(userAgent.contains("msie") ||userAgent.contains("trident")){ names = URLEncoder.encode(names, "UTF-8"); }else{ response.reset(); response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + names+".cer"); } } catch (Exception e) { response.reset(); response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + names+".cer"); } // 在伺服器端建立打包下載的臨時檔案 String outFilePath = request.getSession().getServletContext().getRealPath("/") + "download/"; File file_1 =new File(outFilePath); //如果資料夾不存在則建立 if (!file_1 .exists() && !file_1 .isDirectory()) { System.out.println("//不存在"); file_1 .mkdir(); } File fileZip = new File(outFilePath + names); // 檔案輸出流 FileOutputStream outStream = new FileOutputStream(fileZip); // 壓縮流 ZipOutputStream toClient = new ZipOutputStream(outStream); // toClient.setEncoding("gbk"); zipFilePdf(files, toClient,name); toClient.close(); outStream.close(); this.downloadFiles(fileZip, response, true); return null; }else { List<Map<String, Object>> list = new ArrayList<Map<String,Object>>(); String[] Arrs = id.split(","); for (String FSDYGCXXID : Arrs) { String sql = String.format("select b.FILEPATH,b.FILENAME,a.FSPX,a.FSZH from t_dygcgl_dygcxx_qbs a LEFT JOIN t_sys_files b on a.ID = b.MAINTABLEID WHERE a.FSDYGCXXID = '%s'",FSDYGCXXID ); List<Map<String, Object>> lst= systemService.findForJdbc(sql) ; List<Map<String, Object>> files = new ArrayList<Map<String, Object>>(); List<Map<String, Object>> name = new ArrayList<Map<String, Object>>(); String root = request.getSession().getServletContext().getRealPath("/"); //File Allfile = new File(request.getSession().getServletContext().getRealPath("/")); if(lst!=null && lst.size()>0){ for(int i =0;i<lst.size();i++){ if (lst.get(i).get("FILEPATH") != null) { Map<String, Object> mp = new HashMap<String, Object>(); Map<String, Object> mps = new HashMap<String, Object>(); String url = lst.get(i).get("FILEPATH").toString(); url = StringUtils.substringBefore(url,"."); String urlname = url + ".pdf"; File file = new File(root+urlname); String names = lst.get(i).get("FILENAME").toString(); String fspx = lst.get(i).get("FSPX").toString(); String fszh = lst.get(i).get("FSZH").toString(); mp.put("PATH", file); mps.put("name", names); mps.put("fspx", fspx); mps.put("fszh", fszh); if(file.exists()){ files.add(mp); name.add(mps); } } } } String sqls = String.format("select fsdygcmc from t_dygcgl_dygcxx where id = '%s'",FSDYGCXXID ); Map<String, Object> map = systemService.findOneForJdbc(sqls); String fileName = map.get("fsdygcmc").toString() +"_pdf"+ ".zip"; // 在伺服器端建立打包下載的臨時檔案 String outFilePath = request.getSession().getServletContext().getRealPath("/") + "download/"; File file_1 =new File(outFilePath); //如果資料夾不存在則建立 if (!file_1 .exists() && !file_1 .isDirectory()) { System.out.println("//不存在"); file_1 .mkdir(); } File fileZip = new File(outFilePath + fileName); // 檔案輸出流 FileOutputStream outStream = new FileOutputStream(fileZip); // 壓縮流 ZipOutputStream toClient = new ZipOutputStream(outStream); // toClient.setEncoding("gbk"); zipFilePdf(files, toClient,name); toClient.close(); outStream.close(); Map<String, Object> mp = new HashMap<String, Object>(); mp.put("fileZip", fileZip); list.add(mp); } String fileName = "單元工程pdf合併下載" + ".zip"; String userAgent = request.getHeader("user-agent"); userAgent = userAgent ==null?"":userAgent.toLowerCase(); String names = fileName; try { if(userAgent.contains("msie") ||userAgent.contains("trident")){ names = URLEncoder.encode(names, "UTF-8"); }else{ response.reset(); response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + names+".cer"); } } catch (Exception e) { response.reset(); response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + names+".cer"); } // 在伺服器端建立打包下載的臨時檔案 String outFilePath = request.getSession().getServletContext().getRealPath("/") + "download/"; File file_1 =new File(outFilePath); //如果資料夾不存在則建立 if (!file_1 .exists() && !file_1 .isDirectory()) { System.out.println("//不存在"); file_1 .mkdir(); } File fileZip = new File(outFilePath + names); // 檔案輸出流 FileOutputStream outStream = new FileOutputStream(fileZip); // 壓縮流 ZipOutputStream toClient = new ZipOutputStream(outStream); //toClient.setEncoding("gbk"); zip(list, toClient); toClient.close(); outStream.close(); this.downloadFiles(fileZip, response, true); return null; } } public static void zipFilePdf(List<Map<String, Object>> files, ZipOutputStream outputStream, List<Map<String, Object>> name) throws IOException, ServletException { try { int size = files.size(); // 壓縮列表中的檔案 for (int i = 0; i < size; i++) { File file = (File) files.get(i).get("PATH"); String qbsname = name.get(i).get("name").toString(); String fspx = name.get(i).get("fspx").toString(); String fszh = name.get(i).get("fszh").toString(); zipFilePdf(file, outputStream, qbsname,fspx,fszh); } } catch (IOException e) { throw e; } } public static void zipFilePdf(File inputFile, ZipOutputStream outputstream, String qbsname,String fspx,String fszh) throws IOException, ServletException { try { if (inputFile.exists()) { if (inputFile.isFile()) { FileInputStream inStream = new FileInputStream(inputFile); BufferedInputStream bInStream = new BufferedInputStream(inStream); ZipEntry entrys = new ZipEntry(inputFile.getName()); String entry1 = entrys.toString(); entry1 = StringUtils.substringAfter(entry1,"."); String pathname = qbsname+"_"+fszh+"_("+ fspx+ ")."+entry1; ZipEntry entry = new ZipEntry(pathname); outputstream.putNextEntry(entry); final int MAX_BYTE = 10 * 1024 * 1024; // 最大的流為10M long streamTotal = 0; // 接受流的容量 int streamNum = 0; // 流需要分開的數量 int leaveByte = 0; // 檔案剩下的字元數 byte[] inOutbyte; // byte陣列接受檔案的資料 streamTotal = bInStream.available(); // 通過available方法取得流的最大字元數 streamNum = (int) Math.floor(streamTotal / MAX_BYTE); // 取得流檔案需要分開的數量 leaveByte = (int) streamTotal % MAX_BYTE; // 分開檔案之後,剩餘的數量 if (streamNum > 0) { for (int j = 0; j < streamNum; ++j) { inOutbyte = new byte[MAX_BYTE]; // 讀入流,儲存在byte陣列 bInStream.read(inOutbyte, 0, MAX_BYTE); outputstream.write(inOutbyte, 0, MAX_BYTE); // 寫出流 } } // 寫出剩下的流資料 inOutbyte = new byte[leaveByte]; bInStream.read(inOutbyte, 0, leaveByte); outputstream.write(inOutbyte); outputstream.closeEntry(); // Closes the current ZIP entry // and positions the stream for // writing the next entry bInStream.close(); // 關閉 inStream.close(); } } else { throw new ServletException("檔案不存在!"); } } catch (IOException e) { throw e; } } public void downloadFilepdf(File file,HttpServletResponse response,boolean isDelete) { try { // 以流的形式下載檔案。 BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath())); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // 清空response response.reset(); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes("UTF-8"),"ISO-8859-1")); toClient.write(buffer); toClient.flush(); toClient.close(); if(isDelete) { file.delete(); //是否將生成的伺服器端檔案刪除 } } catch (IOException ex) { ex.printStackTrace(); } }