文件下载器在PHP中下载0 BYTE文件

时间:2014-07-21 09:18:42

标签: php

我的代码不能一直工作。大多数时候它下载0 BYTE图像。我可以通过此代码下载特定图像,也可以是此代码以图标的名称保存图像的大小。如果我重命名图像,则下载0 BYTE。

$file_path= $full_path;

$file = pathinfo($file_path);

$base = $file['basename'];

$dir = $file['dirname'];

header('Content-Description: File Transfer');

header('Content-Type: application/octet-stream');
header("Content-Disposition: attachment; filename=".$base);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: no-cache');
header('Content-Length: ' . filesize($base));
ob_clean();
flush();

$path = $dir."/".$base;

readfile($path);

exit;

1 个答案:

答案 0 :(得分:0)

此代码修复了我的问题....

function download($path)
{
// if file is not readable or not exists
if (!is_readable($path))
    die('File does not exist or it is not readable!');

// get file's pathinfo
$pathinfo = pathinfo($path);
// set file name
$file_name = $pathinfo['basename'];

    $mime = 'application/octet-stream';

// set headers
header('Pragma: public');
header('Expires: -1');
header('Cache-Control: public, must-revalidate, post-check=0, pre-check=0');
header('Content-Transfer-Encoding: binary');
header("Content-Disposition: attachment; filename=\"$file_name\"");
header('Content-Length: ' . filesize($path));
header("Content-Type: $mime");

// read file as chunk to reduce memory usages
if ( $fp = fopen($path, 'rb') ) {
    ob_end_clean();

    while( !feof($fp) and (connection_status()==0) ) {
        print(fread($fp, 8192));
        flush();
    }

    @fclose($fp);
    exit;
}

}

download($file_path);