samsungsamsung 发表于 2015-8-4 07:32:39

org.apache.tools.zip.*和org.apache.commons.httpclient.*实现远程文件打包下载,支持中文文件名(转)

  原文地址:org.apache.tools.zip.*和org.apache.commons.httpclient.*实现远程文件打包下载,支持中文文件名(转)
  


Java代码
[*]package com.kedacom.kdkk.controller.querymanager;   
[*]
[*]import java.io.BufferedInputStream;   
[*]import java.io.BufferedOutputStream;   
[*]import java.io.File;   
[*]import java.io.FileInputStream;   
[*]import java.io.FileOutputStream;   
[*]import java.io.IOException;   
[*]import java.io.InputStream;   
[*]import java.io.OutputStream;   
[*]import java.net.URLEncoder;   
[*]import java.text.DateFormat;   
[*]import java.text.SimpleDateFormat;   
[*]import java.util.ArrayList;   
[*]import java.util.Date;   
[*]import java.util.List;   
[*]import java.util.UUID;   
[*]import java.util.regex.Pattern;   
[*]import java.util.zip.CRC32;   
[*]import java.util.zip.CheckedOutputStream;   
[*]
[*]import javax.servlet.ServletException;   
[*]import javax.servlet.http.HttpServlet;   
[*]import javax.servlet.http.HttpServletRequest;   
[*]import javax.servlet.http.HttpServletResponse;   
[*]
[*]import org.apache.commons.httpclient.HttpClient;   
[*]import org.apache.commons.httpclient.methods.GetMethod;   
[*]
[*]import org.apache.tools.zip.ZipEntry;   
[*]import org.apache.tools.zip.ZipOutputStream;   
[*]
[*]public class BatchDownload extends HttpServlet {   
[*]      
[*]private static List list = new ArrayList();   
[*]Date date = null;   
[*]private static int BUF_SIZE = 40480;   
[*]private static String ZIP_ENCODEING = "GBK";   
[*]
[*]
[*] public BatchDownload() {   
[*]super();   
[*] }   
[*]
[*] public void doGet(HttpServletRequest request, HttpServletResponse response)   
[*]   throws ServletException, IOException {   
[*]    //设置编码   
[*]    request.setCharacterEncoding("utf-8");   
[*]    date =new Date();   
[*]    //设置下载头信息   
[*]    response.setContentType("application/octet-stream");   
[*]    response.setHeader("Content-Disposition", "attachment; filename=\""+date.getTime()+".zip\"");   
[*]    //要打包下载的图片json参数   
[*]    String cbxStr = request.getParameter("cbxStr");   
[*]    if(cbxStr.length() > 0){   
[*]      cbxStr = cbxStr.substring(0, cbxStr.length()-1);   
[*]      String [] cbxs = cbxStr.split(";");   
[*]         HttpClient client = new HttpClient();   
[*]         GetMethod get = null;   
[*]         //创建本地存储文件路径   
[*]         new File("d:/vehicleImgs/"+date.getTime()+"/").mkdir();   
[*]         for(int i = 0; i < cbxs.length; i ++){   
[*]             try {      
[*]               //构建远程服务的图片下载路径   
[*]               String cbxs2 [] = cbxs.split("z");   
[*]               String vid = cbxs2[0];   
[*]               String timestamp = cbxs2[1];   
[*]               String imgtype = cbxs2[2].split(",")[0];   
[*]               String imgName = cbxs2[3];   
[*]               imgName = imgName.replace(" ", "_").replace(":", "_");   
[*]               DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
[*]               Long timeStamp = format1.parse(timestamp).getTime();   
[*]               String imgUrl = getServletContext().getInitParameter("opticmServer");                  
[*]               //此方法的参数可自行传入,参数值为远程服务的servlet(xxx.do),返回的值为文件流对象   
[*]               get = new GetMethod(imgUrl+"&contentId="+vid+"&imgType="+imgtype+"&imgOrder=0&timeStamp="+timeStamp);      
[*]               int j = client.executeMethod(get);                                 
[*]               if (200 == j)//是否正确返回                                                      
[*]                  {                                                                  
[*]                      File storeFile = new File("d:/vehicleImgs/"+date.getTime()+"/"+imgName+".jpg");   
[*]                      FileOutputStream output = new FileOutputStream(storeFile);   
[*]                      // 得到网络资源的字节数组,并写入文件                           
[*]                      output.write(get.getResponseBody());                           
[*]                      output.close();         
[*]                  }else{                                                                  
[*]                      System.out.println("no pic");                                 
[*]                  }                                                            
[*]            } catch ( Exception e ){                                                                     
[*]                  System.out.println("Exception no pic");                                    
[*]            } finally{   
[*]                  get.releaseConnection();   
[*]            }   
[*]         }   
[*]       try {   
[*]         //开始压缩下载下来的本机图片   
[*]          zip("d:\\vehicleImgs\\"+date.getTime()+".zip", new File("d:\\vehicleImgs\\"+date.getTime()+"\\"));   
[*]          //下载zip打包后的文件   
[*]          FileInputStream fis = new FileInputStream("d:\\vehicleImgs\\"+date.getTime()+".zip");   
[*]             byte[] bytes=new byte;   
[*]             int r = 0;      
[*]             response.flushBuffer();   
[*]             while((r=fis.read(bytes))>0) {   
[*]                response.getOutputStream().write(bytes,0,r);   
[*]             }   
[*]             fis.close();   
[*]             response.getOutputStream().close();   
[*]    } catch (Exception e) {   
[*]      e.printStackTrace();   
[*]    }   
[*]    }   
[*] }   
[*]
[*] /**   
[*]      * 压缩文件或文件夹
[*]      *   
[*]      * @param zipFileName
[*]   * @param inputFile
[*]   * @throws Exception
[*]   */   
[*]    public void zip(String zipFileName, File inputFile) throws Exception {   
[*]      // 未指定压缩文件名,默认为"ZipFile"      
[*]      if (zipFileName == null || zipFileName.equals(""))   
[*]            zipFileName = "ZipFile";   
[*]   
[*]      // 添加".zip"后缀      
[*]      if (!zipFileName.endsWith(".zip"))   
[*]            zipFileName += ".zip";   
[*]   
[*]      // 创建文件夹      
[*]      File f = null;   
[*]      String path = Pattern.compile("[\\/]").matcher(zipFileName).replaceAll(File.separator);   
[*]      int endIndex = path.lastIndexOf(File.separator);   
[*]      path = path.substring(0, endIndex);   
[*]      f = new File(path);   
[*]      f.mkdirs();   
[*]      // 开始压缩      
[*]       {   
[*]             ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileName)));   
[*]             zos.setEncoding(ZIP_ENCODEING);   
[*]             compress(zos, inputFile, "");   
[*]             zos.close();   
[*]         }   
[*]    }   
[*]    /**   
[*]         * 压缩一个文件夹或文件对象到已经打开的zip输出流 不建议直接调用该方法
[*]         *   
[*]         * @param zos
[*]         * @param f
[*]         * @param fileName
[*]         * @throws Exception
[*]         */   
[*]      public void compress(ZipOutputStream zos, File f, String fileName) throws Exception {   
[*]            if (f.isDirectory()) {   
[*]                // 压缩文件夹      
[*]               File[] fl = f.listFiles();   
[*]                zos.putNextEntry(new ZipEntry(fileName + "/"));   
[*]                fileName = fileName.length() == 0 ? "" : fileName + "/";   
[*]                for (int i = 0; i < fl.length; i++) {   
[*]                  compress(zos, fl, fileName + fl.getName());   
[*]                }   
[*]            } else {   
[*]                // 压缩文件      
[*]                zos.putNextEntry(new ZipEntry(fileName));   
[*]                FileInputStream fis = new FileInputStream(f);   
[*]                this.inStream2outStream(fis, zos);   
[*]                zos.flush();   
[*]                fis.close();   
[*]                zos.closeEntry();   
[*]            }   
[*]      }   
[*]         
[*]      public void inStream2outStream(InputStream is, OutputStream os) throws IOException {   
[*]            BufferedInputStream bis = new BufferedInputStream(is);   
[*]            BufferedOutputStream bos = new BufferedOutputStream(os);   
[*]            int bytesRead = 0;   
[*]            for (byte[] buffer = new byte; ((bytesRead = bis.read(buffer, 0, BUF_SIZE)) != -1);) {   
[*]                bos.write(buffer, 0, bytesRead); // 将流写入      
[*]            }   
[*]      }   
[*]
[*]   
[*] public void doPost(HttpServletRequest request, HttpServletResponse response)   
[*]   throws ServletException, IOException {   
[*]this.doGet(request, response);   
[*] }   
[*]}   
  下载:
ant.jar (1009.8 KB)
  
BatchDownload.rar (2.6 KB)
  
页: [1]
查看完整版本: org.apache.tools.zip.*和org.apache.commons.httpclient.*实现远程文件打包下载,支持中文文件名(转)