主要用到函数
opendir — 打开目录句柄
readdir — 从目录句柄中读取条目
closedir — 关闭目录句柄
filectime — 取得文件的 inode 修改时间
in_array — 检查数组中是否存在某个值
pathinfo — 返回文件路径的信息
file_exists — 检查文件或目录是否存在
is_uploaded_file — 判断文件是否是通过 HTTP POST 上传的
move_uploaded_file — 将上传的文件移动到新位置
getimagesize — 取得图像信息,大小
readfile — 输出一个文件
//2.重设响应类型
header('Content-type:'.$fileInfo['mime']);
//3.执行下载的文件名
header('Content-Disposition:attachment; filename='.$_GET['name']);
//4.指定文件大小
header('Content-Length:'. filesize($file));
文件介绍
index.php主要遍历文件列表信息, 上传单表
doupload.php 主要处理文件上传
download.php 主要处理文件下载
index.php
<html>
<head>
<title>图片上传和下载示例</title>
</head>
<body>
<h2>图片上传和下载示例</h2>
<form action="doupload.php" method="post" enctype="multipart/form-data" >
上传图片:<input type="file" name="pic" />
<input type="submit" value="上传" />
</form>
<table width="500" border="0">
<tr align="left" bgcolor="#ccc">
<th>序号</th>
<th>图片</th>
<th>创建时间</th>
<th>操作</th>
</tr>
<?php
//打开目录
$dir = opendir("./uploads");
//遍历目录
$i = 0;
while ($f = readdir($dir)) {
if ($f != '.' && $f != '..') {
$i++;
echo '<tr>';
echo '<td>' . $i . '</td>';
echo '<td><img src="./uploads/' . $f . '" width=80 height=50 /></td>';
echo '<td>' . date('Y-m-d H:i:s', filectime('./uploads/' . $f)) . '</td>';
echo '<td><a href="./uploads/' . $f . '">查看</a> <a href="download.php?name=' . $f . '">下载</a></td>';
echo '</tr>';
}
}
//关闭目录
closedir($dir);
?>
<tr align="left" bgcolor="#ccc">
<td colspan="4"> </td>
</tr>
</table>
</body>
</html>
doupload.php
<?php
//1 获取文件信息
$upfile = $_FILES['pic'];
$typeList = array('image/jpg', 'image/jpeg', 'image/gif', 'image/png');
$path = './uploads/';
$maxFileSize = 1024000;
//2过滤上传文件的错误号
if ($upfile['error'] > 0) {
switch ($upfile['error']) {
case 1 :
$info = '上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值。 ';
break;
case 2 :
$info = '上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。 ';
break;
case 3 :
$info = '文件只有部分被上传 ';
break;
case 4 :
$info = '没有文件被上传 ';
break;
case 6 :
$info = '找不到临时文件夹';
break;
case 7 :
$info = '文件写入失败。';
break;
}
}
//3上传文件大小过滤
if ($upfile['size'] > $maxFileSize){
die('上传文件超出限制');
}
//4文件类型过滤
if (!in_array($upfile['type'], $typeList)){
die('上传文件类型不允许'.$upfile['type']);
}
//5上传后的文件名定义
$pathinfo = pathinfo($upfile['name']);
do{
$newFile = date('YmdHis'). rand(1000, 9999).'.'.$pathinfo['extension'];
} while (file_exists($path.$newFile));
//6执行上传文件
if (is_uploaded_file($upfile['tmp_name'])){ //判断文件是否是通过 HTTP POST 上传的
if (move_uploaded_file($upfile['tmp_name'], $path.$newFile)){
echo '上传文件成功';
echo '<h3><a href="index.php">返回</a></h3>';
} else {
die('上传文件失败');
}
} else {
die('这不是一个上传文件');
}
?>
download.php
<?php
//执行文件下载
//1.获取要下载的图片名
$file = './uploads/'.$_GET['name'];
//2.重设响应类型
$fileInfo = getimagesize($file);
header('Content-type:'.$fileInfo['mime']);
//3.执行下载的文件名
header('Content-Disposition:attachment; filename='.$_GET['name']);
//4.指定文件大小
header('Content-Length:'. filesize($file));
//5.响应内容
readfile($file);
?>