PHP 文件下载 header设置
1、已知.txt文件路径,点击时弹出下载框下载该文件。
public function downloadAction(){
$file_path = $_GET['url']; //文件路径
$file_name = trim($_GET['title']).'.txt'; //文件名;或直接从路径上获取 basename($file_path)
header("Content-type: text/plain"); //Mime-Type类型
header("Content-Disposition:attachment;filename = ".$file_name); //弹出保存框的形式下载文件(附件)
readfile($file_path); //返回从文件中读入的字节数
die(); //方法结束
}
2、已经.txt文件的路径,点击时在浏览器打开(查看)该文件。
header("Content-Disposition:inline;filename = ".$file_name); //在页面内打开文件
总结:Content-Disposition属性有两种类型:inline 和 attachment
- inline :将文件内容直接显示在页面;
- attachment:弹出对话框让用户下载。
3、下载较大的视频文件。引用
/**
* @todo 下载文件
* @param string $file 文件路径
*/
public function download($file){ //引用 https://blog.csdn.net/zhanqixuan22/article/details/47753927
set_time_limit(0); //程序最大的执行时间,单位为秒。如果设置为0(零),没有时间方面的限制。
ini_set('memory_limit', '512M'); // 最大单线程的独立内存使用量。也就是一个web请求,给予线程最大的内存使用量的定义。
header('Content-Type: application/octet-stream'); //octet-stream:是以流的形式下载文件,这样可以实现任意格式的文件下载。
header('Content-Disposition: attachment; filename='.basename($file)); //以浏览器弹出保存框形式下载文件。
header('Content-Transfer-Encoding: binary'); //内容在传输过程中的编码格式
readfile($file); //返回从文件中读入的字节数
}