我欲乘风九万里
梦的起点
心灵之声
珊瑚礁
编码之舞
梦中的微风
项目编码
聚合登录文档
建议
AI助手
php实现数据流下载
##### 第一种方法 推荐使用 ```php public function file($filePath,$orginalName=false) { if($orginalName) { $pathInfo = pathinfo($filePath); $filename = $pathInfo['basename']; } else { $filename = date('YmdHis').'.png'; } // 检查文件是否存在 if (file_exists($filePath)) { $ext = pathinfo($filePath, PATHINFO_EXTENSION); $ext = strtolower($ext); if($ext=='jpeg') { header('Content-Type: image/jpeg'); } elseif ($ext=='png') { header('Content-Type: image/png'); } elseif ($ext=='gif') { header('Content-Type: image/gif'); } elseif ($ext=='webp') { header('Content-Type: image/webp'); } $fileHandle = fopen($filePath, "rb"); if ($fileHandle === false) { exit("Can not open file: $filePath"); } if(in_array($ext,['png','jpeg','jpg','webp'])) { header('Content-type:application/octet-stream;'); } else { header('Content-type:application/octet-stream;charset=' . "utf-8"); } header("Content-Transfer-Encoding: binary"); header("Accept-Ranges: bytes"); //文件大小 header("Content-Length: " . filesize($filePath)); //触发浏览器文件下载功能 header('Content-Disposition:attachment;filename="' . urlencode($filename) . '"'); // 非常重要, 否则会出现 ZWNBSP (图片下载,显示文件已损坏) ob_clean(); flush(); //循环读取文件内容,并输出 while (!feof($fileHandle)) { //从文件指针 handle 读取最多 length 个字节(每次输出10k) echo fread($fileHandle, 10240); } //关闭文件流 fclose($fileHandle); } else { // 文件不存在时的处理 throw new \Exception('File not found.'); } } ``` 第二种方法 当确定下载的文件大小不大时可以使用 ```php public function file3($file) { // 检查文件是否存在 if (file_exists($file)) { // 获取文件名 $filename = basename($file); // 设置响应头,告诉浏览器下载文件 header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . $filename); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); // 打开文件并输出到浏览器 readfile($file); exit; } else { // 文件不存在时的处理 echo 'File not found.'; } } ```
ysian
我雾化科所
1
聚合登录之创建应用篇
2024-07-30
645
0
2
php函数之match
2024-07-29
583
0
3
聚合登录之常见问题
2024-07-30
489
0
4
聚合登录之前后端示例代码
2024-07-30
483
0
5
聚合登录之获取登录链接
2024-07-30
422
0
6
服务器瘦身
2023-11-01
414
5
7
centos下升级openssl
2023-11-30
414
0
8
我的第一篇博客
2023-09-28
403
0
9
supervisor的安装与使用
2023-11-02
384
0
10
editor.md 代码块没有下拉框
2023-10-06
352
2
PHP [9]
linux [4]
sh [1]
闲谈 [1]
css [2]
redis [2]
Cluster集群 [1]
git [1]
centos [1]
webman [2]
工具 [1]
OAuth2.0 [1]
项目 [1]
初始化 [1]
thinkphp [1]
Nginx [1]
往事 [1]
Mysql [1]
支付宝 [2]
抖音 [2]
qq [2]
聚合 [1]
登录 [1]
聚合登录 [4]
cache [1]
html [1]
queue [1]
Workerman版本
4.1.15
Webman版本
1.5.9
PHP版本
8.3.6
MYSQL版本
8.2.24
操作系统
CENTOS