FileController.class.php 2.64 KB
<?php
/**
 * 【后台】下载中心下载文件
 * FileController.class.php
 * @author:heyuelong
 * @date:2018年4月18日16:28:41
 */

namespace Frontend\Controller\Export;

use Common\Common\ExportDownload;
use Common\Service\DownloadService;
use Org\Net\PHPZip;

class FileController extends \Common\Controller\Frontend\AbstractController
{
    protected $_require_login = false;

    public function Index()
    {
        $id = I('get.id');

        // 实例化
        $service = new DownloadService();

        // 获取详情
        $info = $service->get($id);

        // 初始化扩展后缀
        $ext = '.xls';

        if (ExportDownload::ZIP_TYPE == $info['type']) {

            $phpzip = new PHPZip();

            // 组装压缩文件名称
            $filename = get_sitedir() . microtime(true) . '.zip';

            // 打包文件
            $phpzip->zipDir($info['url'], $filename, false);

            $ext = '.zip';

            // 下载文件
            $this->down_load($info, $filename, $ext);

            // 删除文件
            unlink($filename);
            exit;
        } elseif (ExportDownload::PDF_TYPE == $info['type']) {

            $ext = '.pdf';
        }

        $filename = $info['url'];

        // 下载文件
        $this->down_load($info, $filename, $ext);

        exit;
    }

    /**
     * 下载文件功能
     * @param array $info
     * @param string $filePath 文件地址
     * @param string $ext 文件后缀
     */
    protected function down_load($info = [], $filePath = '', $ext = '.xls')
    {
        // 文件下载
        if (!file_exists($filePath)) {
            exit("下载失败");
        }

        $filename = $info['title'] . $ext;
        $fileNameEncode = urlencode($filename);
        $fileNameEncode = str_replace('+', '%20', $fileNameEncode);
        $userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        if (stripos($userAgent, 'Firefox') !== false) {
            $dispositionFileName = 'filename*="utf8\'\'' . $filename . '"';
        } else {
            $dispositionFileName = 'filename="' . $fileNameEncode . '"';
        }
        unset($filename, $fileNameEncode);

        $file = fopen($filePath, "r");
        Header("Content-type: application/octet-stream");
        Header("Accept-Ranges: bytes");
        Header("Accept-Length: " . filesize($filePath));
        Header("Content-Disposition: attachment; {$dispositionFileName}");
        echo fread($file, filesize($filePath));
        $buffer = 1024;
        while (!feof($file)) {
            $file_data = fread($file, $buffer);
            echo $file_data;
        }
        fclose($file);
    }
}