文件打包下载



    @ResponseBody
    @RequestMapping(value = "/downloadAll.json")
    public AjaxResponse downloadFileAll(String serverPath, HttpServletRequest request,
            HttpServletResponse response) {
        AjaxResponse ajaxResponse = new AjaxResponse();
//调用文件打包方法
            String downloadtemp = downloadtemp(serverPath);
      //调用文件下载的方法下载这个zip
            String result = Utility.downloadSingleFile(downloadtemp, request, response);
            if (result != null) {
                ajaxResponse.setSuccess(true);
            } else{
                ajaxResponse.setSuccess(false);
                ajaxResponse.setData("下载失败,文件不存在");
            }

        return ajaxResponse;
    }

    // 文件打包
    public String downloadtemp(String filePath) {
        String[] filepath = filePath.split(",");

        File[] file = new File[filepath.length];
        // 服务器根路径
        String root = PropertiesUtil.getInstance().loadProperties(UPLOAD_PATH, "upload_path_root");
        String dir = PropertiesUtil.getInstance().loadProperties(UPLOAD_PATH, "upload_path_dir");
        String project = PropertiesUtil.getInstance().loadProperties(UPLOAD_PATH, "upload_path_project");

        // 如果一级目录不存在,创建
        File temp = new File(root + dir);
        if (!temp.exists() && !temp.isDirectory()) {
            temp.mkdir();
        }
        dir += project;
        // 如果二级目录不存在,创建
        temp = new File(root + dir);
        if (!temp.exists() && !temp.isDirectory()) {
            temp.mkdir();
        }

        SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        dir += sFormat.format(date) + "/";

        // 如果三级目录不存在,创建
        temp = new File(root + dir);
        if (!temp.exists() && !temp.isDirectory()) {
            temp.mkdir();
        }
        String filepa=dir + "AllData.zip";
        try {

            // 下载的压缩包的路径
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(root + dir + "AllData.zip"));
            byte[] buffer = new byte[1024];
            for (int i = 0; i < filepath.length; i++) {
                file[i] = new File(root + filepath[i]);
            }

            for (int i = 0; i < file.length; i++) {
                FileInputStream fis = new FileInputStream(file[i]);
                out.putNextEntry(new ZipEntry(file[i].getName()));
                // 设置压缩文件内的字符编码,不然会变成乱码
                // out.setEncoding("GBK");
                int len;
                // 读入需要下载的文件的内容,打包到zip文件
                while ((len = fis.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
                out.closeEntry();
                fis.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return filepa;
    }

猜你喜欢

转载自blog.csdn.net/mr_yarnell/article/details/74553340
今日推荐