多文件下载------打包下载

@RequestMapping("/batchDownLoad")
    @ResponseBody
    public void batchDownLoad(HttpServletRequest request,HttpServletResponse response,String fileNames) {

        Map<String,String> map=new HashMap<>();
        String[] files=fileNames.split(",");
        for(String fileName:files){ 
        //将多个文件的文件名和地址放入map集合,以便打包时使用,其中SysFileUtils是自己封装的获取文件路径的方法,大家可以根据自己的习惯来定义
            map.put(fileName,SysFileUtils.getFilePath()+ fileName);   
//下载的压缩包的名称,可根据自己的需求自行更改
        String fileName = "批量下载.zip";
        //获取文件路径,此处为的文件路径为压缩包的临时路径
        String realPath = request.getSession().getServletContext().getRealPath("/");
        try {
        //调用文件打包方法
            zipFile(map,realPath,fileName);
        realPath = realPath + fileName;
        //以流的形式下载文件
        BufferedInputStream fis = new BufferedInputStream(new FileInputStream(realPath));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        //清空
         response.reset();
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());response.setContentType("application/octet-stream");
         response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"),"ISO-8859-1"));
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
        } catch (Exception e) {

            e.printStackTrace();
        }
    }
 /**
     * 文件打包
     * @author niuyuhui
     * @param map
     * @param rootPath
     * @param fileName
     * @throws Exception
     */
    public void zipFile(Map  map, String rootPath, String fileName) throws Exception{
        File zipFile = new File(rootPath + "/" + fileName);
        if (zipFile.exists()) {
            zipFile.delete();
        }
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(rootPath + "/" + fileName));
        ZipEntry ze = null;
        byte[] buf = new byte[1024];
        int readLen = 0;
        for (Map.Entry entry : map.entrySet()) {
            ze = new ZipEntry(entry.getKey());//设置下载文件名称
            zos.putNextEntry(ze);
            String absoluteFileName = entry.getValue();//文件绝对路径
            InputStream is = new BufferedInputStream(new FileInputStream(absoluteFileName));
            while ((readLen = is.read(buf, 0, 1024)) != -1) {
                zos.write(buf, 0, readLen);
            }
            is.close();
        }
        zos.close();
    }

你可能感兴趣的:(java)