zoukankan      html  css  js  c++  java
  • org.apache.tools.zip.*和org.apache.commons.httpclient.*实现远程文件打包下载,支持中文文件名(转)

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

     

    Java代码  
    1. package com.kedacom.kdkk.controller.querymanager;   
    2.   
    3. import java.io.BufferedInputStream;   
    4. import java.io.BufferedOutputStream;   
    5. import java.io.File;   
    6. import java.io.FileInputStream;   
    7. import java.io.FileOutputStream;   
    8. import java.io.IOException;   
    9. import java.io.InputStream;   
    10. import java.io.OutputStream;   
    11. import java.net.URLEncoder;   
    12. import java.text.DateFormat;   
    13. import java.text.SimpleDateFormat;   
    14. import java.util.ArrayList;   
    15. import java.util.Date;   
    16. import java.util.List;   
    17. import java.util.UUID;   
    18. import java.util.regex.Pattern;   
    19. import java.util.zip.CRC32;   
    20. import java.util.zip.CheckedOutputStream;   
    21.   
    22. import javax.servlet.ServletException;   
    23. import javax.servlet.http.HttpServlet;   
    24. import javax.servlet.http.HttpServletRequest;   
    25. import javax.servlet.http.HttpServletResponse;   
    26.   
    27. import org.apache.commons.httpclient.HttpClient;   
    28. import org.apache.commons.httpclient.methods.GetMethod;   
    29.   
    30. import org.apache.tools.zip.ZipEntry;   
    31. import org.apache.tools.zip.ZipOutputStream;   
    32.   
    33. public class BatchDownload extends HttpServlet {   
    34.        
    35. private static List list = new ArrayList();   
    36. Date date = null;   
    37. private static int BUF_SIZE = 40480;     
    38. private static String ZIP_ENCODEING = "GBK";     
    39.   
    40.   
    41.  public BatchDownload() {   
    42.   super();   
    43.  }   
    44.   
    45.  public void doGet(HttpServletRequest request, HttpServletResponse response)   
    46.    throws ServletException, IOException {   
    47.     //设置编码   
    48.     request.setCharacterEncoding("utf-8");   
    49.     date =  new Date();   
    50.     //设置下载头信息   
    51.     response.setContentType("application/octet-stream");   
    52.     response.setHeader("Content-Disposition""attachment; filename=\""+date.getTime()+".zip\"");   
    53.     //要打包下载的图片json参数   
    54.     String cbxStr = request.getParameter("cbxStr");   
    55.     if(cbxStr.length() > 0){   
    56.         cbxStr = cbxStr.substring(0, cbxStr.length()-1);   
    57.         String [] cbxs = cbxStr.split(";");   
    58.          HttpClient client = new HttpClient();   
    59.          GetMethod get = null;   
    60.          //创建本地存储文件路径   
    61.          new File("d:/vehicleImgs/"+date.getTime()+"/").mkdir();   
    62.          for(int i = 0; i < cbxs.length; i ++){   
    63.              try {      
    64.                  //构建远程服务的图片下载路径   
    65.                  String cbxs2 [] = cbxs[i].split("z");   
    66.                  String vid = cbxs2[0];   
    67.                  String timestamp = cbxs2[1];   
    68.                  String imgtype = cbxs2[2].split(",")[0];   
    69.                  String imgName = cbxs2[3];   
    70.                  imgName = imgName.replace(" ""_").replace(":""_");   
    71.                  DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    
    72.                  Long timeStamp = format1.parse(timestamp).getTime();   
    73.                  String imgUrl = getServletContext().getInitParameter("opticmServer");                    
    74.                  //此方法的参数可自行传入,参数值为远程服务的servlet(xxx.do),返回的值为文件流对象   
    75.                  get = new GetMethod(imgUrl+"&contentId="+vid+"&imgType="+imgtype+"&imgOrder=0&timeStamp="+timeStamp);       
    76.                  int j = client.executeMethod(get);                                  
    77.                  if (200 == j)//是否正确返回                                                       
    78.                   {                                                                  
    79.                       File storeFile = new File("d:/vehicleImgs/"+date.getTime()+"/"+imgName+".jpg");   
    80.                       FileOutputStream output = new FileOutputStream(storeFile);     
    81.                       // 得到网络资源的字节数组,并写入文件                           
    82.                       output.write(get.getResponseBody());                           
    83.                       output.close();         
    84.                   }else{                                                                  
    85.                       System.out.println("no pic");                                  
    86.                   }                                                              
    87.               } catch ( Exception e ){                                                                      
    88.                   System.out.println("Exception no pic");                                      
    89.               } finally{   
    90.                   get.releaseConnection();    
    91.               }   
    92.          }   
    93.        try {   
    94.            //开始压缩下载下来的本机图片   
    95.           zip("d:\\vehicleImgs\\"+date.getTime()+".zip", new File("d:\\vehicleImgs\\"+date.getTime()+"\\"));   
    96.           //下载zip打包后的文件   
    97.           FileInputStream fis = new FileInputStream("d:\\vehicleImgs\\"+date.getTime()+".zip");    
    98.              byte[] bytes=new byte[BUF_SIZE];   
    99.              int r = 0;      
    100.              response.flushBuffer();   
    101.              while((r=fis.read(bytes))>0) {   
    102.                 response.getOutputStream().write(bytes,0,r);   
    103.              }   
    104.              fis.close();    
    105.              response.getOutputStream().close();   
    106.     } catch (Exception e) {   
    107.         e.printStackTrace();   
    108.     }     
    109.     }   
    110.  }   
    111.   
    112.  /**   
    113.       * 压缩文件或文件夹   
    114.       *    
    115.       * @param zipFileName   
    116.      * @param inputFile   
    117.      * @throws Exception   
    118.      */     
    119.     public void zip(String zipFileName, File inputFile) throws Exception {     
    120.         // 未指定压缩文件名,默认为"ZipFile"      
    121.         if (zipFileName == null || zipFileName.equals(""))     
    122.             zipFileName = "ZipFile";     
    123.     
    124.         // 添加".zip"后缀      
    125.         if (!zipFileName.endsWith(".zip"))     
    126.             zipFileName += ".zip";     
    127.      
    128.         // 创建文件夹      
    129.         File f = null;   
    130.         String path = Pattern.compile("[\\/]").matcher(zipFileName).replaceAll(File.separator);     
    131.         int endIndex = path.lastIndexOf(File.separator);     
    132.         path = path.substring(0, endIndex);     
    133.         f = new File(path);   
    134.         f.mkdirs();     
    135.         // 开始压缩      
    136.        {     
    137.              ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileName)));     
    138.              zos.setEncoding(ZIP_ENCODEING);     
    139.              compress(zos, inputFile, "");   
    140.              zos.close();     
    141.          }     
    142.     }     
    143.     /**   
    144.          * 压缩一个文件夹或文件对象到已经打开的zip输出流 <b>不建议直接调用该方法</b>   
    145.          *    
    146.          * @param zos   
    147.          * @param f   
    148.          * @param fileName   
    149.          * @throws Exception   
    150.          */     
    151.         public void compress(ZipOutputStream zos, File f, String fileName) throws Exception {     
    152.             if (f.isDirectory()) {     
    153.                 // 压缩文件夹      
    154.                File[] fl = f.listFiles();     
    155.                 zos.putNextEntry(new ZipEntry(fileName + "/"));     
    156.                 fileName = fileName.length() == 0 ? "" : fileName + "/";     
    157.                 for (int i = 0; i < fl.length; i++) {     
    158.                     compress(zos, fl[i], fileName + fl[i].getName());     
    159.                 }     
    160.             } else {     
    161.                 // 压缩文件      
    162.                 zos.putNextEntry(new ZipEntry(fileName));     
    163.                 FileInputStream fis = new FileInputStream(f);     
    164.                 this.inStream2outStream(fis, zos);     
    165.                 zos.flush();   
    166.                 fis.close();     
    167.                 zos.closeEntry();     
    168.             }     
    169.         }     
    170.          
    171.         public void inStream2outStream(InputStream is, OutputStream os) throws IOException {     
    172.             BufferedInputStream bis = new BufferedInputStream(is);     
    173.             BufferedOutputStream bos = new BufferedOutputStream(os);     
    174.             int bytesRead = 0;     
    175.             for (byte[] buffer = new byte[BUF_SIZE]; ((bytesRead = bis.read(buffer, 0, BUF_SIZE)) != -1);) {     
    176.                 bos.write(buffer, 0, bytesRead); // 将流写入      
    177.             }     
    178.         }     
    179.   
    180.     
    181.  public void doPost(HttpServletRequest request, HttpServletResponse response)   
    182.    throws ServletException, IOException {   
    183.   this.doGet(request, response);   
    184.  }   
    185. }   

    下载:

  • ant.jar (1009.8 KB)
  • BatchDownload.rar (2.6 KB)
查看全文
  • 相关阅读:
    ibatis.net:惯用法
    ibatis.net:在VS中支持xml智能提示
    设计原则:色彩
    编码原则:“防御式编程”再次让我快乐
    错误:update 忘了加 where
    .NET:不要使用扩展方法扩展Object对象。
    错误:不小心的VS重命名
    技术人生:如何更有效率的切换上下文?
    Logstash filter 插件之 grok
    轻松测试 logstash 的配置文件
  • 原文地址:https://www.cnblogs.com/beijia/p/BatchLoad.html
  • Copyright © 2011-2022 走看看