从服务器打包下载文件

接上篇附件上传,附件下载代码向下看

/**
 * 文件下载
 */
public class FileDownload {
    @Autowired
    ServletContext context;
    /**
     * 打包下载多条数据(ids)中的附件
     * 附件信息单独保存在附件表中,主表只存了附件的id
     * 附件表存储规则:附件实际名称,附件id名称(防止附件重名,服务器存储的附件用 id.后缀 的方式存储)
     * @param response
     * @param ids 
     */
    public void download(HttpServletResponse response, String ids) {
        try {
            String path1 = context.getRealPath("/");    //实际路径
            File upload = new File(new File(path1).getAbsolutePath(), "upload/pub/");
            long sj = System.currentTimeMillis();
            String filePath = upload.getAbsolutePath() + File.separator + "cjda" + File.separator + sj;
            String zipfile = upload.getAbsolutePath() + File.separator + "allsj" + sj + ".zip";
            createFolder(filePath);

            List<String> fjIds = new ArrayList<String>();// 查询附件id(fjIds)
            List<String> inputFile = new ArrayList<String>(); // 用于存储需打包的文件
            for (String fjid : fjIds) {
                Upload_pubPage uploadPage = new Upload_pubPage(); // 根据fjid获取附件实体
                InputStream is = new FileInputStream(upload.getAbsolutePath() + File.separator + uploadPage.getCcm());// 服务器上的文件(fjId.后缀)
                String fileName = filePath + File.separator + uploadPage.getXsm(); // 预下载文件(实际的文件名.后缀)
                OutputStream os = new FileOutputStream(fileName);
                try {
                    // 写入附件
                    byte[] buffer = new byte[1024];
                    int byteRead = is.read(buffer);
                    if (byteRead == -1) {
                        break;
                    }
                    os.write(buffer, 0, byteRead);
                }
                catch (MalformedURLException e) {
                    e.printStackTrace();
                } finally {
                    is.close();
                    os.close();
                }
                inputFile.add(fileName);
            }
            // 添加到压缩包
            ToZIP(inputFile, zipfile);

            response.setCharacterEncoding("UTF-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName="+ URLEncoder.encode("试卷.zip", "UTF-8"));
            int len;
            byte[] buffer = new byte[8];
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(zipfile));
            OutputStream os = response.getOutputStream(); //输出流
            while ((len = bis.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建目录
     * @param destDirName 目标目录名
     * @return 创建成功返回true,否则返回false
     */
    public static boolean createFolder(String destDirName) {
        File dir = new File(destDirName);
        if (dir.exists()) {
            return false;
        }
        if (dir.mkdirs()) { // 创建成功
            return true;
        } else {
            return false;
        }
    }

    /**
     * 压缩ZIP包
     *
     * @param inputFile 输入文件列表
     * @param zipfile   输出的压缩文件
     * @return
     */
    public static boolean ToZIP(List<String> inputFile, String zipfile) {
        File file = null;
        try {
            file = new File(zipfile);
            // 创建文件输出流
            FileOutputStream fous = new FileOutputStream(file);
            ZipOutputStream zipOut = new ZipOutputStream(fous);
            for (String s : inputFile) {
                File f = new File(s);
                compress(f, f.getName(), zipOut, true);
            }
            zipOut.close();
            fous.close();
        } catch (Exception e) {
            e.printStackTrace();
            if (null != file) {
                file.delete();
            }
            return false;
        }
        return true;
    }

    /**
     * 递归压缩方法
     *
     * @param sourceFile 源文件
     * @param zos zip输出流
     * @param name 压缩后的名称
     * @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
     * 					false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws Exception
     */
    private static void compress(File sourceFile, String name, ZipOutputStream zos, boolean KeepDirStructure)
            throws Exception {

        byte[] buf = new byte[10240];
        if (sourceFile.isFile()) {
            // 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
            zos.putNextEntry(new ZipEntry(name));
            // copy文件到zip输出流中
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1) {
                zos.write(buf, 0, len);
            }
            // Complete the entry
            zos.closeEntry();
            in.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if (listFiles == null || listFiles.length == 0) {
                // 需要保留原来的文件结构时,需要对空文件夹进行处理
                if (KeepDirStructure) {
                    // 空文件夹的处理
                    zos.putNextEntry(new ZipEntry(name + "/"));
                    // 没有文件,不需要文件的copy
                    zos.closeEntry();
                }
            } else {
                for (File file : listFiles) {
                    // 判断是否需要保留原来的文件结构
                    if (KeepDirStructure) {
                        // 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
                        // 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
                        compress(file, name + "/" + file.getName(), zos, KeepDirStructure);
                    } else {
                        compress(file, file.getName(), zos, KeepDirStructure);
                    }
                }
            }
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
网站服务器打包zip是指将一个网站的文件和数据打包成zip格式的压缩包,以便于传输、备份或者部署到其他服务器打包一个网站服务器可以将网站的所有文件文件夹和数据库内容进行整合和压缩,确保文件完整性和一致性。这样可以方便地备份和恢复网站,在数据迁移或部署新服务器时也能够快速地进行操作。 打包网站服务器时,首先需要收集和整理网站的所有文件和数据。这包括网站的源代码、图片、视频、音频、文档等各种类型的文件,以及数据库中存储的所有数据。然后,将这些文件和数据按照目录结构进行组织,确保文件间的关联关系不会丢失。最后,使用压缩软件将这些文件和数据打包成zip格式的压缩包。 打包网站服务器后,可以方便地将这个zip压缩包传输到其他服务器。通过将整个网站以压缩包的形式传输,可以减少传输过程中的文件丢失或损坏的风险。同时,也减少了传输的时间和带宽消耗。在目标服务器上,只需解压缩该zip包,即可恢复网站的完整性和功能。 此外,打包网站服务器也能够帮助网站迁移或部署到其他服务器。通过将整个网站服务器以zip包的形式打包,可以更加方便地将网站的文件和数据迁移到新的服务器上。无论是更新服务器的硬件,还是更换服务提供商,都能够更加快捷地进行操作,减少迁移带来的停机时间。 综上所述,网站服务器打包zip是一种方便快捷的方式,能够帮助我们备份、传输和部署网站服务器

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值