php实现文件下载,PHP实现文件下载

简单的示例代码:

function downloadFile($filePath)

{

set_time_limit(0);

if (substr($filePath, strlen($filePath) - 1) == '/') {

$filePath = substr($filePath, 0, strlen($filePath) - 1);

}

if (!is_file($filePath) && !is_readable($filePath)) {

return false;

}

$obj = new SplFileInfo($filePath);

header('Content-Type: application/octet-stream');

header('Accept-Ranges:bytes');

header('Content-Length:' . filesize($filePath)); //注意是'Content-Length:' 非Accept-Length

header('Content-Disposition:attachment;filename=' . $obj->getFilename());//声明作为附件处理和下载后文件的名称

$buffer = 1024;

ob_clean();

$handle = fopen($filePath, 'rb');

while (!feof($handle)) {

echo fread($handle, $buffer);

}

flush();

fclose($handle);

exit;

}

主要是设置header头:

文件类型:Content-Type: application/octet-stream

字节流:Accept-Ranges:bytes

长度:Content-Length:>0

声明作为附件处理和下载后文件的名称:

Content-Disposition:attachment;filename=FILENAME

*最重要的是 ob_clean();跟flush();

如果没有这两个函数,有可能下载下来的文件就是损坏的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值