您的位置:首页 > 编程语言 > Java开发

springmvc批量将文件打包成zip下载

2016-12-26 15:28 357 查看
springMVC的代码

 /**

  * 一键下载图片

  */

 @SuppressWarnings("unchecked")

 @RequestMapping(value = "downUrl")

 @CheckLogin

 public void admin_applyloan_downUrl(HttpServletRequest request,

   HttpServletResponse response,

   @RequestParam(value = "id", required = true) Long id) {

  try {

   //1.获取项目中文件的文件夹

   String basePath = request.getSession().getServletContext().getRealPath("/") + Constants.RESOURCE_PATH;

   //2.获取oss上的文件路径List集合:https://www.xxx.xx/xxx.jpg

   ApplyLoan applyLoan = applyLoanService.getById(id);

   List<String> urlListAll = new ArrayList<String>();

   List<String> urlList = (List<String>) applyLoan.getParamsMap().get("carImg");

   List<String> ownerList = (List<String>) applyLoan.getParamsMap().get("ownerImg");

   urlListAll.addAll(urlList);

   urlListAll.addAll(ownerList);

   //3.定义文件list

   List<File> files = new ArrayList<File>();

   //4.定义zip文件名

   String fileName = UUID.randomUUID().toString() + ".zip";

   //4.1定义临时单个文件的list,方便后面删除

   List<String> tempUrlList = new ArrayList<String>();

   //5.将文件从https上下载进服务器的目录,用files装好

   for (String url : urlListAll) {

    URL u = new URL((String) request.getServletContext().getAttribute("imagePath") + url);

    String tempUrl = basePath +System.currentTimeMillis()+ url.substring(url.lastIndexOf("."));

    File f = new File(tempUrl);

    if(!f.exists()){

     try {

      f.createNewFile();

     } catch (IOException e) {

      e.printStackTrace();

     }

    }

    InputStream ins = u.openStream();

    OutputStream os = new FileOutputStream(f);

    int bytesRead = 0;

    byte[] buffer = new byte[2048];

    while ((bytesRead = ins.read(buffer, 0, 2048)) != -1) {

     os.write(buffer, 0, bytesRead);

    }

    os.close();

    ins.close();

    files.add(f);

    tempUrlList.add(tempUrl);

   }

   //6.创建zip文件

   ZipUtil.createFile(basePath, fileName);

   File file = new File(basePath + fileName);

   FileOutputStream outStream = new FileOutputStream(file);

   ZipOutputStream toClient = new ZipOutputStream(outStream);

   //7.将files打包成zip文件

   ZipUtil.zipFile(files, toClient);

   toClient.close();

   outStream.close();

   //8.下载zip文件,并删除服务器源文件

   ZipUtil.downloadFile(file, response, true);

   //9.删除服务器临时的单个文件

   for(String t : tempUrlList){

    DeleteFileUtil.delete(t);

   }

  } catch (Exception e) {

   e.printStackTrace();

  }

 }

/**

 * @version 1.0

 * 删除文件 

 * */

public class DeleteFileUtil {

 /**

   * 删除文件,可以是文件或文件夹

   * @param fileName 要删除的文件名

   * @return 删除成功返回true,否则返回false

   */ 

  public static boolean delete(String fileName) { 

    File file = new File(fileName); 

    if (!file.exists()) { 

     System.out.println("删除文件失败:" + fileName + "不存在!"); 

     return false; 

    } else { 

     if (file.isFile()) 

      return deleteFile(fileName); 

     else 

      return deleteDirectory(fileName); 

    }

  }

}

zip压缩代码

/**

 * zip压缩文件

 */

public class ZipUtil {

 
 /**

  * 压缩文件列表中的文件

  *

  * @param files

  * @param outputStream

  * @throws IOException

  */

 public static void zipFile(List<File> files, ZipOutputStream outputStream)

   throws IOException, ServletException {

  try {

   int size = files.size();

   // 压缩列表中的文件

   for (int i = 0; i < size; i++) {

    File file = (File) files.get(i);

    zipFile(file, outputStream);

   }

  } catch (IOException e) {

   throw e;

  }

 }
 /**

  * 将文件写入到zip文件中

  *

  * @param inputFile

  * @param outputstream

  * @throws Exception

  */

 public static void zipFile(File inputFile, ZipOutputStream outputstream)

   throws IOException, ServletException {

  try {

   if (inputFile.exists()) {

    if (inputFile.isFile()) {

     FileInputStream inStream = new FileInputStream(inputFile);

     BufferedInputStream bInStream = new BufferedInputStream(

       inStream);

     ZipEntry entry = new ZipEntry(inputFile.getName());

     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;

  }

 }
 /**

  * 下载文件

  *

  * @param file

  * @param response

  */

 public static void downloadFile(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();

  }

 }

 

 /**

  *  创建文件

  * @param path

  * @param fileName

  */

 public static void createFile(String path, String fileName) {

  File f = new File(path);

  File file = new File(f, fileName);

  if (!file.exists()) {

   try {

    file.createNewFile();

   } catch (IOException e) {

    e.printStackTrace();

   }

  }
 }
}

以上就可以从别的服务器,采用地址批量打包下载代码了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: