java压缩多文件打包下载

/**
 * 压缩文件列表中的文件
 * @param files
 * @param outputStream
 * @throws IOException
 */
public static void zipFile(List files, ZipOutputStream outputStream, List<String> fileurls) throws IOException,ServletException
{
    try{
        int size = files.size();
        //压缩列表中的文件
        for(int i = 0; i < size; i++){
            File file = (File) files.get(i);
            if(file.exists()){
                if(file.isFile()){
                    FileInputStream inStream = new FileInputStream(file);
                    BufferedInputStream bInStream = new BufferedInputStream(inStream);
                    ZipEntry entry = new ZipEntry(file.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;
    }
}

//在服务器端创建临时压缩文件 返回下载路径

@RequestMapping("/downLoadZipFile")
@ResponseBody
public Object piliangdownload(String fileIds) {
    Map<String, Object> map1 = new HashMap<>();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    String outFilePath = "";
    try {
        List<Map<String, Object>> list = filesService.getFileList(fileIds, null);
        if (list != null && list.size() > 0) {
            List<File> files = new ArrayList<File>();
            List<String> fileurls = new ArrayList<String>();
            for (Map<String, Object> map : list) {
                File file = new File(map.get("name").toString());
                File sourcefile = new File(PathUtil.getClasspath() + map.get("url"));//上传的原文件
                if (sourcefile.exists()) {
                    int byteread = 0;
                    InputStream inStream = new FileInputStream(sourcefile); //读入原文件
                    FileOutputStream fs = new FileOutputStream(file);
                    byte[] buffer = new byte[1444];
                    while ((byteread = inStream.read(buffer)) != -1) {
                        fs.write(buffer, 0, byteread);
                    }
                    inStream.close();

                    files.add(file);
                }
            }
            //在服务器端创建打包下载的临时文件
            outFilePath = "D:/" + sdf.format(new Date()) + ".zip";
            File file = new File(outFilePath);
            //文件输出流
            FileOutputStream outStream = new FileOutputStream(file);
            //压缩流
            ZipOutputStream toClient = new ZipOutputStream(outStream);
            toClient.setEncoding("gbk");
            zipFile(files, toClient, fileurls);
            toClient.close();
            outStream.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ServletException e) {
        e.printStackTrace();
    }
    if (StringToolUtils.isNotBlanks(outFilePath)) {
        String[] str = outFilePath.split("/");
        map1.put("zipName", str[str.length - 1]);
        map1.put("outFilePath", outFilePath);
        return responseMap(1, "200", "压缩成功", map1);
    } else {
        return responseMap(2, "400", "压缩失败", null);
    }

}
//下载打包好的zip文件,下载完成之后从服务器端删除压缩文件
@RequestMapping("/downloadZip")
public Object downloadZip(String url,HttpServletRequest request) {
  //文件名称
   SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
   InputStream in=null;
   try {
      in=new FileInputStream(new File(url));
        byte[] body=null;
        body=new byte[in.available()];
        in.read(body);

      String[]  strs=url.split("/");
      String fileName=new String(strs[strs.length-1].getBytes("gbk"),"iso8859-1");
        HttpHeaders headers=new HttpHeaders();
        headers.add("Content-Disposition", "attachment;filename="+fileName);
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> response=new ResponseEntity<byte[]>(body, headers, statusCode);
      return response;
   }catch(Exception e) {
      LOG.info(e.getMessage());
      return responseMap(400, "1", "下载失败", null);
   }finally {
      IOUtils.closeQuietly(in);
      File file = new File(url);
      file.delete();
   }
}

//重名文件需要注意

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值