PHP脚本实现服务器文件下载

一个简单的view界面

<html>
<head>
<title>文件下载</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>

</head>
<body>
<h1>文件下载首页</h1>

<a href="FileProcess.php?file_name=11.bmp&file_sub_dir=/filedown/down/">点击下载</a><img src="down/11.bmp" width="100px" height="80px"><br/>

<a href="FileProcess.php?file_name=22.bmp&file_sub_dir=/filedown/down/">点击下载</a><img src="down/22.bmp" width="100px" height="80px"><br/>

 


</body>

</html>

 

数据处理界面:

 

<?php

$file_name=$_REQUEST['file_name'];
$file_sub_dir=$_REQUEST['file_sub_dir'];

//echo $file_name."||".$file_sub_dir;
if(isset($file_name) && isset($file_sub_dir)){
  down_file($file_name,$file_sub_dir);
}

//函数说明:
 // 1:$file_name :文件名
 // 2:$file_sub_dir: 要下载文件的子路径
function down_file($file_name,$file_sub_dir){
 header("content-type:text/html;charset=utf-8");
 //$file_name="12.png";
// $file_name=iconv("utf-8","gb2312",$filename);
 //$file_path=$_SERVER['DOCUMENT_ROOT']."/objects/down/".$file_name;
 $file_path=$_SERVER['DOCUMENT_ROOT'].$file_sub_dir.$file_name;
 if(!file_exists($file_path)){
   echo "所选择的文件不存在!";
   //exit();
   return;
 }

 $fp=fopen($file_path,"r");
 $file_size=filesize($file_path);
 //echo "文件的大小为:".($file_size/1024)."kb";
//返回的文件
if($file_size>30*1024*1024){
 echo "<script language='javascript'>window.alert('文件过大');</script>";
 exit();
}
header("Content-type: application/octet-stream");
//按照字节大小返回
header("Accept-Ranges: bytes");
//返回文件的大小
header("Accept-Length: $file_size");
//这里客户端的弹出对话框,对应的文件名。
header("Content-Disposition: attachment;filename=".$file_path);

//put the data of server return to Browser.
$buffer=$file_size;
if(!feof($fp)){
  $file_data=fread($fp,$buffer);
  echo $file_data;
}
//close file.
fclose($fp);

 }
?>

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值