標籤:src while 下載 dir xxx ted 需求 new https
需求:從伺服器下載圖片。
因為項目前期設定的問題,導致各個項目的圖片是分開存放的。客戶要求根據項目下載,實現項目下分地方,然後地方目錄下是圖片
@ResponseBodypublic void downloadUrl(HttpServletResponse response, HttpServletRequest request){ String sourceFilePath=properties.getString("sourceFilePath");//要下載的檔案路徑 eavlProName = xxx;//項目名 String downloadName = "xxx.zip"; //下載檔案名稱 String agent = request.getHeader("USER-AGENT"); //瀏覽器核心資訊 try { if (agent.contains("MSIE")||agent.contains("Trident")) {// IE downloadName = java.net.URLEncoder.encode(downloadName, "UTF-8"); } else { downloadName = new String(downloadName.getBytes("UTF-8"),"ISO-8859-1"); } } catch (Exception e) { e.printStackTrace(); } zip(sourceFilePath, eavlProName, response, downloadName); response.getOutputStream().close(); //這個應該沒什麼用}private void zip(String souceFileName, String eavlProName, HttpServletResponse response, String downloadName) { File file = new File(souceFileName); try { zip(file, eavlProName, response, downloadName); } catch (IOException e) { e.printStackTrace(); } } private void zip(File souceFile, String eavlProName, HttpServletResponse response, String downloadName) throws IOException { ZipOutputStream out = null; //設定壓縮流。 response.setHeader("Content-Disposition", "attachment;fileName=\"" + downloadName + "\""); try { out = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream())); out.setMethod(ZipOutputStream.DEFLATED); //設定壓縮方法 } catch (Exception e) { e.printStackTrace(); } out.setEncoding("gbk"); zip(souceFile, out, eavlProName, eavlProName,null); out.closeEntry(); out.close(); } private void zip(File souceFile, ZipOutputStream out, String base, String eavlProName, Integer i) throws IOException { if (souceFile.isDirectory()) { File[] files = souceFile.listFiles(); if (files.length != 0) { if (i == null || i != 1) { //對於地方目錄先不建立,當地方目錄下存在項目的時,才建立 out.putNextEntry(new ZipEntry(base + "/")); base = base.length() == 0 ? "" : base + "/"; } if (i == null) { i = 0; } i++; for (File file : files) { if (i == null || i != 2) { //2地方下面的項目名.這種不建立目錄 zip(file, out, base + file.getName(), eavlProName, i); }else { String picPathname =file.getName(); if (picPathname.equals(eavlProName)) { //取對應項目下的檔案 zip(file, out, base, eavlProName, i); } } } } } else { if (base.length() > 0) { out.putNextEntry(new ZipEntry(base)); } else { out.putNextEntry(new ZipEntry(souceFile.getName())); } FileInputStream in = new FileInputStream(souceFile); int b; byte[] by = new byte[1024]; while ((b = in.read(by)) != -1) { out.write(by, 0, b); } in.close(); } }
參考:http://www.jianshu.com/p/7cabe09ce563
JAVA實現邊下載邊壓縮