zoukankan      html  css  js  c++  java
  • PHP在线批量下载文件

    在项目开发中需要给客户提供在线下载文件的功能。

    解决方案:使用PHP自带的ZipArchive类,将多个文件打包成zip文件,供客户下载!

    使用ZipArchive类时,需要先开启php_zip扩展,没有php_zip.dll扩展的可自行下载。下载完成后将php_zip.dll文件放入PHP的ext扩展文件夹下,然后在php.ini中添加 extension=php_zip.dll,重启nginx或Apache完成扩展的安装。

    下面直接上代码:

    public function download()
    {
    $id = $this->request->get('id');
    $path = DrawModel::get($id)->path; //文件存放路径

    $paths = explode(',', $path);
    $file_lj = str_replace("\","/",ROOT_PATH.'public');

    $zipname = $file_lj . '/files/test.zip'; //这里要预先创建一个.zip文件
    //$zipname = addslashes($zipname);
    $zip = new ZipArchive();
    $res = $zip->open($zipname, ZipArchive::OVERWRITE); //坑一:之所以不用ZipArchive::CREATE模式,是因为ZipArchive::CREATE模式会不断往test.zip中追加内容
    if ($res === TRUE) {
    foreach ($paths as $path) {

    $new_filename = substr($path, strrpos($path, '/') + 1);
    $zip->addFile($file_lj.$path, $new_filename); //坑二:addFile的第一个参数一定要是绝对路径(保证能通过该路径找到相应的文件)
    }
    $zip->close();
    header("Content-Type: application/zip");
    header("Content-Transfer-Encoding: Binary");

    header("Content-Length: " . filesize($zipname));
    header("Content-Disposition: attachment; filename="" . basename($zipname) . """);

    readfile($zipname);
    exit;
    }

    }

    注意:使用ZipArchive类时别忘了引入 use ZipArchive

  • 相关阅读:
    python print 在命令行打印带颜色
    Cython 一篇通
    gcc 内置函数
    gcc 内置函数
    #define xxx do{...} while(0) 宏定义
    防止cpu 一直被占用 sleep(0) 和 yield
    golang之archive/tar包的使用
    go+mysql实现页面的增删改查练习
    设计模式之访问者模式
    设计模式之模板模式(PHP实现)
  • 原文地址:https://www.cnblogs.com/lty-fly/p/12021279.html
Copyright © 2011-2022 走看看