精华内容
下载资源
问答
  • Java下载压缩文件

    2020-12-18 18:14:51
    Java下载压缩文件 List<File> files = new ArrayList<>(); String fileName = URLEncoder.encode("文件名" + dateToDayString + ".zip", "UTF-8"); response.setContentType("multipart/form-data"); ...

    Java下载压缩文件

    List<File> files = new ArrayList<>();
    String fileName = URLEncoder.encode("文件名" + dateToDayString + ".zip", "UTF-8");
    response.setContentType("multipart/form-data");
    response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
    response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
    response.setHeader("Pragma", "public");
    response.setDateHeader("Expires", (System.currentTimeMillis() + 10000));
    // 使用有权限目录
    String videoPath = "csv" + "/";
    zipComponent.downLoadFiles(files, response, nasPath + videoPath, fileName);
    
    package com.sf.argus.web.component;
    
    import java.io.*;
    import java.util.List;
    import java.util.zip.GZIPInputStream;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;
    
    import javax.servlet.http.HttpServletResponse;
    
    import cn.hutool.core.io.FileUtil;
    import cn.hutool.core.io.IoUtil;
    import cn.hutool.http.HttpRequest;
    import cn.hutool.http.HttpResponse;
    import cn.hutool.http.HttpUtil;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    
    @Component
    @Slf4j
    public class ZipComponent {
        private String cosDomainProxy;
        private String nasPath;
        private String csv;
    
        public HttpServletResponse downLoadFiles(List<File> files, HttpServletResponse response, String zipPath,String zipName) {
    
            String zipFilename = zipPath + zipName;
            File file = new File(zipFilename);
            try (FileOutputStream fileOut = new FileOutputStream(file)) {
                log.info("准备新建下载");
                if (!file.exists()) {
                    file.createNewFile();
                    log.info("新建完成");
                }
                response.reset();
                // 创建文件输出流
                ZipOutputStream zipOut = new ZipOutputStream(fileOut);
                zipFile(files, zipOut);
                zipOut.close();
                fileOut.close();
                log.info("压缩文件是否生成:{} 文件大小:{}" , file.exists(),file.length());
                return downloadZip(file, response);
            } catch (Exception e) {
                log.error("downLoadFiles error", e);
            }
            return response;
        }
        /**
         * 把接受的全部文件打成压缩包
         */
        public void zipFile(List<File> files, ZipOutputStream outputStream) {
            int size = files.size();
            for (int i = 0; i < size; i++) {
                File file = files.get(i);
                zipFile(file, outputStream);
            }
        }
    
        /**
         * 根据输入的文件与输出流对文件进行打包
         */
        public void zipFile(File inputFile, ZipOutputStream outputStream) {
            InputStream inputStream = null;
            BufferedInputStream bins = null;
            try {
                String path = inputFile.getPath();
                StringBuilder sb = new StringBuilder();
                sb.append(cosDomainProxy).append(path);
                HttpRequest get = HttpUtil.createGet(sb.toString());
                HttpResponse execute = get.execute();
                log.info("path:{} from proxy read file status:{}", path, execute.getStatus());
                if (!execute.isOk()) {
                    return;
                }
                inputStream = execute.bodyStream();
                bins = new BufferedInputStream(inputStream, 512);
                ZipEntry entry = new ZipEntry(inputFile.getName());
                outputStream.putNextEntry(entry);
                int nNumber;
                byte[] buffer = new byte[512];
                while ((nNumber = bins.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, nNumber);
                }
            } catch (Exception e) {
                log.error("zipFile error", e);
            } finally {
                // 关闭创建的流对象
                try {
                    if (bins != null) {
                        bins.close();
                    }
                    if (inputStream != null) {
                        inputStream.close();
                    }
                } catch (IOException e) {
                    log.error("zipFile error", e);
                }
            }
        }
    
        public HttpServletResponse downloadZip(File file, HttpServletResponse response) {
            if (!file.exists()) {
                log.info("待压缩的文件目录:{}不存在", file);
            } else {
                try (InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()))) {
                    // 以流的形式下载文件。
                    byte[] buffer = new byte[fis.available()];
                    while (fis.read(buffer) > 0) {
                        response.reset();
                        try (OutputStream toClient = new BufferedOutputStream(response.getOutputStream())) {
                            response.setContentType("application/octet-stream");
                            // 如果输出的是中文名的文件,在此处就要用URLEncoder.encode方法进行处理
                            response.setHeader("Content-Disposition",
                                "attachment;filename=" + new String(file.getName().getBytes("GB2312"), "ISO8859-1"));
                            toClient.write(buffer);
                            toClient.flush();
                        }
                    }
                } catch (IOException ex) {
                    log.error("downloadZip error", ex);
                } finally {
                    try {
                        File f = new File(file.getPath());
                        f.delete();
                    } catch (Exception e) {
                        log.error("delete file error", e);
                    }
                }
            }
            return response;
        }
    }
    
    展开全文
  • Java 下载压缩文件

    千次阅读 2018-06-06 17:22:31
    String zipFile :将要压缩成的文件位置 “地址/name.zip” String zipFrontFile : 将要压缩成的文件名称 “name.zip” List srcfile : 要压缩文件集合 HttpServletResponse response : 请求的响应 try{ ...

    部分代码:
    String zipFile :将要压缩成的文件位置 “地址/name.zip”
    String zipFrontFile : 将要压缩成的文件名称 “name.zip”
    List srcfile : 要压缩的文件集合
    HttpServletResponse response : 请求的响应

    try{
        byte[] buf = new byte[2048];
          // 创建值班单zip文件
          ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
          // 循环压缩文件
          for (int i = 0; i < srcfile.size(); i++) {
            File file = srcfile.get(i);
            FileInputStream in = new FileInputStream(file);
            // 添加压缩包文件
            out.putNextEntry(new ZipEntry(file.getName()));
            int len = 0;
            while ((len = in.read(buf)) > 0) {
              out.write(buf, 0, len);
            }
            // 关闭入口
            out.closeEntry();
            // 关闭文件流
            in.close();
          }
          // 关闭文件流
          out.close();
          // 写出文件到前台
          InputStream ins = new FileInputStream(zipFile);
          //  放到缓冲流里面 
          BufferedInputStream bins = new BufferedInputStream(ins);
          //  获取文件输出IO流
          OutputStream outs = response.getOutputStream();
          BufferedOutputStream bouts = new BufferedOutputStream(outs);
          // 设置response内容的类型
          response.setContentType("application/x-download");
          response.setHeader("Content-disposition",
              "attachment;filename=" + URLEncoder.encode(zipFrontFile, "UTF-8"));
          int bytesRead = 0;
          byte[] buffer1 = new byte[2048];
          // 开始向网络传输文件流
          while ((bytesRead = bins.read(buffer1, 0, 2048)) > 0) {
            bouts.write(buffer1, 0, bytesRead);
          }
          bouts.flush();
          ins.close();
          bins.close();
          outs.close();
          bouts.close();
        } catch (Exception e) {
         // logger.error("异常", e);
        } finally {
          // 删除zip和文件及删除目录
          ToolUtils.deleteFiles(fileDirPath);
        }
    }
    
    /**
    *删除zip和文件及删除目录
    */
    public static boolean deleteFiles(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
          return flag;
        }
        if (!file.isDirectory()) {
          file.delete();
          return true;
        }
        String[] fileList = file.list();
        File temFile = null;
        for (int i = 0; i < fileList.length; i++) {
          if (path.endsWith(File.separator)) {
            temFile = new File(path + fileList[i]);
          } else {
            temFile = new File(path + File.separator + fileList[i]);
          }
          if (temFile.isFile()) {
            temFile.delete();
          }
        }
        file.delete();
        return flag;
      }
    展开全文
  • java下载压缩文件

    2016-01-06 11:12:41
    @RequestMapping(value = {"/downloadImg.html"}, method = {RequestMethod.GET, RequestMethod.POST})... public void downloadImg(HttpServletRequest request, HttpServletResponse response) throws Exception{  
    @RequestMapping(value = {"/downloadImg.html"}, method = {RequestMethod.GET, RequestMethod.POST})
    public void downloadImg(HttpServletRequest request, HttpServletResponse response) throws Exception{
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000);
        response.setContentType("APPLICATION/OCTET-STREAM");
    response.setHeader("Content-Disposition", "attachment; filename="+ newFileName + ".zip");
    ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
    File[] files = new File[2];
    files[0] = new File("D:\\pd1.jpg");
    files[1] = new File("D:\\pd2.jpg");
    for (int i = 0; i < files.length; i++) {
    File f = files[i];
    zos.putNextEntry(new ZipEntry(f.getName()));
    FileInputStream fis = new FileInputStream(f);
    byte[] buffer = new byte[1024];
    int r = 0;
    while ((r = fis.read(buffer)) != -1) {
    zos.write(buffer, 0, r);
    }
    fis.close();
    }
    zos.flush();
    zos.close(); 
        }
    展开全文
  • java 下载压缩文件后打开报 不可预料的压缩文件末端 如图所示: [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lGIsmKva-1593490158214)(C:\Users\Administrator\AppData\Roaming\Typora\...

    java 下载压缩文件后打开报 不可预料的压缩文件末端

    如图所示:

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lGIsmKva-1593490158214)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20200629165351623.png)]

    背景:使用了ZipOutputStream将文件打包压缩成zip文件。使用了ByteArrayOutputStream将zip作为 文件流缓存到内存中。然后通过ByteArrayOutputStream的toByteArray()方法获取字节数组并base64编码方便接口调用。调用方解码获取字节数组再转换成对应文件。

    原代码:

    public static final String uploadFolder = "D:/booking/uploadFiles/";
    //id为路径下要下载的文件名
    public static Map downloadzip(String id) throws Exception {
            //完整路径
            String realpath = uploadFolder + id ;
            //文件流保存到字节数组缓存区
            ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
            ZipOutputStream zos = new ZipOutputStream(arrayOutputStream);
        //获取路径下所有的文件
            List<File> list = path(realpath);
        //压缩   
        try {
                for (File f:list) {
                    byte[] buf = new byte[1024];
                    zos.putNextEntry(new ZipEntry(f.getName()));
                    int len;
                    FileInputStream in = new FileInputStream(f);
                    while ((len = in.read(buf)) != -1){
                        zos.write(buf, 0, len);
                    }
                    zos.closeEntry();
                    in.close();
                }
            } finally {
                byte[] bytes = arrayOutputStream.toByteArray();
                //base64编码
                String encode = new BASE64Encoder().encode(bytes);
                HashMap<String, String> map = new HashMap<>();
                map.put("base64str",encode);
                map.put("filename","attachment.zip");
                zos.close();
                return map;
            }
        
        public static   List<File> path(String filepath)  {
            ArrayList<File> list = new ArrayList<>();
            File file = new File(filepath);
            if (!file.isDirectory()) {
    
            } else if (file.isDirectory()) {
                String[] filelist = file.list();
                for (int i = 0; i < filelist.length; i++) {
                    File readfile = new File(filepath + "/" + filelist[i]);
                    if (!readfile.isDirectory()) {
                        list.add(readfile);
                    } else if (readfile.isDirectory()) {
                        path(filepath + "/" + filelist[i]);
                    }
                }
            }
            return list;
        }
    

    修改后:

    public static final String uploadFolder = "D:/booking/uploadFiles/";
    //id为路径下要下载的文件名
    public static Map downloadzip(String id) throws Exception {
            //完整路径
            String realpath = uploadFolder + id ;
            //文件流保存到字节数组缓存区
            ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
            ZipOutputStream zos = new ZipOutputStream(arrayOutputStream);
        //获取路径下所有的文件
            List<File> list = path(realpath);
        //压缩   
        try {
                for (File f:list) {
                    byte[] buf = new byte[1024];
                    zos.putNextEntry(new ZipEntry(f.getName()));
                    int len;
                    FileInputStream in = new FileInputStream(f);
                    while ((len = in.read(buf)) != -1){
                        zos.write(buf, 0, len);
                    }
                    zos.closeEntry();
                    in.close();
                }
            } finally {
            //先关闭资源再获取字节码
            	zos.close();
                byte[] bytes = arrayOutputStream.toByteArray();
                //base64编码
                String encode = new BASE64Encoder().encode(bytes);
                HashMap<String, String> map = new HashMap<>();
                map.put("base64str",encode);
                map.put("filename","attachment.zip");
                return map;
            }
        
        public static   List<File> path(String filepath)  {
            ArrayList<File> list = new ArrayList<>();
            File file = new File(filepath);
            if (!file.isDirectory()) {
    
            } else if (file.isDirectory()) {
                String[] filelist = file.list();
                for (int i = 0; i < filelist.length; i++) {
                    File readfile = new File(filepath + "/" + filelist[i]);
                    if (!readfile.isDirectory()) {
                        list.add(readfile);
                    } else if (readfile.isDirectory()) {
                        path(filepath + "/" + filelist[i]);
                    }
                }
            }
            return list;
        }
    

    调用代码:

    @GetMapping("download/{id}")
        public void downLoad(@PathVariable("id") String id) throws Exception {
            Map map = UploadAndDownloadUtil.downloadzip("62bffdf76e894faaa75e061bd1b5c771");
            String filebase64 = (String) map.get("base64str");
            byte[] bytes = new BASE64Decoder().decodeBuffer(filebase64);
            FileOutputStream out = new FileOutputStream(new File("D:\\booking\\uploadFiles\\62bffdf76e894faaa75e061bd1b5c773\\fujian.zip"));
            out.write(bytes);
            out.close();
            System.out.println(JSON.toJSONString(map));
        }
    

    差异是关闭ZipOutputStream流的顺序变了。在finally块中arrayOutputStream在执行toByteArray();之前要先关闭ZipOutputStream对象。然后就可以愉快的做下载功能 了。

    展开全文
  • 亲测可用,下载的文件名不要重复,重复的话会报错:java.util.zip.ZipException: duplicate entry: xxx.pdf public Map<String,Object> downloadFile(HttpServletRequest request, HttpServletResponse ...
  • java 文件压缩下载

    千次阅读 2017-12-22 16:56:43
    java文件压缩下载
  • Java后台文件批量压缩下载

    万次阅读 2020-08-28 09:31:29
    页面如下,勾选对应的复选框,点击批量下载按钮,即可将复选框对应的附件批量压缩成一个zip压缩包,然后浏览器弹框下载。 前端 // 批量下载 $("#downloadBtn").click(function () { // 获取复选选框对应的ID ...
  • 主要为大家详细介绍了java压缩文件下载图片示例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
  • Java文件压缩下载

    2012-03-27 09:42:18
    Java文件压缩下载 2010-11-03 15:23:31| 分类: java | 标签: |字号大中小 订阅 . 承接上文,上文书中说到struts的文件批量上传,接下来总结一下java文件压缩下载功能,既把文件打成压缩包然后下载,实现中...
  • java生成压缩文件

    万次阅读 2013-07-29 21:15:35
    在工作过程中,需要将一个文件夹生成压缩文件,然后提供给用户下载。所以自己写了一个压缩文件的工具类。该工具类支持单个文件和文件夹压缩。放代码: import java.io.BufferedOutputStream; import java.io.File...
  • java压缩文件下载

    2020-03-25 10:40:22
    //设置压缩流:直接写入response,实现边压缩下载 ZipOutputStream zipos = null; DataOutputStream os = null; URL url = null; InputStream input = null; try { zipos = new ZipOutputStream(new ...
  • 在工作过程中,需要将一个文件夹生成压缩文件,然后提供给用户下载。下面通过实例代码给大家介绍Java生成压缩文件的方法,感兴趣的朋友一起看看吧
  • 在工作过程中,需要将一个文件夹生成压缩文件,然后提供给用户下载。写了一个压缩文件的工具类。该工具类支持单个文件和文件夹压缩
  • 当我们对一些需要用到的资料进行整理时,会发现文件的内存占用很大,不过是下载或者存储,都不是很方便,这时候我们会想到把文件变成zip格式,即进行压缩。在正式开始压缩下载文件之前,我们可以先对zip的格式进行...
  • Java文件压缩下载解决方案

    千次阅读 2018-09-07 18:00:33
    会员运营平台经过改版后页面增加了许多全部下载链接,上周上线比较仓促,全部下载是一个直接下载ZIP压缩文件的链接,每个ZIP压缩文件都是由公司运营人员将页面需要下载的文件全部压缩成一个ZIP压缩文件,然后通过...
  • java压缩文件

    2019-09-29 11:57:22
    因为是第三方平台,解决中文乱码问题,所以需要下载 ant.jar 包,直接百度下载即可 package cn.com.decompression; import java.io.BufferedOutputStream;import java.io.File;import java.io.FileOutputStream;...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 4,151
精华内容 1,660
关键字:

java下载压缩文件

java 订阅