PHP 怎样实现图片下载,而不是打开!

WBOY
Release: 2016-06-23 14:10:58
Original
982 people have browsed it

如题:
PHP 如何实现指定的图片下载?而不是在浏览器中打开?


回复讨论(解决方案)

<?php    $file = "/tmp/dummy.tar.gz";    header("Content-type: application/octet-stream");    header('Content-Disposition: attachment; filename="' . basename($file) . '"');    header("Content-Length: ". filesize($file));    readfile($file);
Copy after login

给你贴出一段韩顺平在讲php下载的案例,希望能够帮助你。如果你需要看视频,可以看韩顺平php视频教程第87讲:
代码如下:

//对函数的说明
//参数说明 $file_name 文件名
//$file_sub_dir: 下载文件的子路径  '"/xxx/xxx/"
function down_file($file_name,$file_sub_dir){

//死去活来,演示下载一个图片.
//如果文件是中文.



//原因 php文件函数,比较古老,需要对中文转码 gb2312
$file_name=iconv("utf-8","gb2312",$file_name);

//绝对路径
$file_path=$_SERVER['DOCUMENT_ROOT'][
].$file_sub_dir.$file_name;

//1.打开文件
if(!file_exists($file_path)){
echo "文件不存在!";
return ;
}
     
$fp=fopen($file_path,"r");
  //2.处理文件
//获取下载文件的大小
$file_size=filesize($file_path);

if($file_size>30){

echo "<script>window.alert('过大')</script>";
return ;
}

//返回的文件
header("Content-type: application/octet-stream");
//按照字节大小返回
header("Accept-Ranges: bytes");
//返回文件大小
header("Accept-Length: $file_size");
//这里客户端的弹出对话框,对应的文件名
header("Content-Disposition: attachment; filename=".$file_name);


//向客户端回送数据

$buffer=1024;
//为了下载的安全,我们最好做一个文件字节读取计数器
$file_count=0;
//这句话用于判断文件是否结束
while(!feof($fp) && ($file_size-$file_count>0) ){
$file_data=fread($fp,$buffer);
//统计读了多少个字节
$file_count+=$buffer;
//把部分数据回送给浏览器;
echo $file_data;
}

//关闭文件
fclose($fp);

}

//测试函数是否可用
down_file("顺平.jpg","/http/down/");

?>

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!