学习总结
- 文件上传操作封装在类中利于使用和维护
- 文件批量上传时前端的input中写multiple参数
- 文件上传时前端form必须是POST方式上传,
method="POST" enctype="multipart/form-data"
,而且表单发送前的编码方式必须是二进制编码。
1.单文件上传类 upFException.php
<?php
namespace compotents\conn
{
include 'upFException.php';
class UploadFile
{
private $oriFileName;//原始文件名
private $fileType;//文件类型
private $error;//错误类型
private $tmpFileName;//临时文件名
private $fileSize;//已上传文件大小
public function __construct($file)
{
$this->oriFileName = $file['name'];
$this->fileType = $file['type'];
$this->error = $file['error'];
$this->tmpFileName = $file['tmp_name'];
$this->fileSize = $file['size'];
}
public function checkSuccess($fileType):bool//检测文件是否上传成功
{
$error = $this->error;
$type = strstr($this->fileType,'/',true);
try {
if ($error > UPLOAD_ERR_OK) :
switch ($error) :
case UPLOAD_ERR_INI_SIZE:
throw new upFException('上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值', 1);
break;
case UPLOAD_ERR_FORM_SIZE:
throw new upFException('上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值', 2);
break;
case UPLOAD_ERR_PARTIAL:
throw new upFException('文件只有部分被上传', 3);
break;
case UPLOAD_ERR_NO_FILE:
throw new upFException('没有文件被上传', 4);
break;
case UPLOAD_ERR_NO_TMP_DIR:
throw new upFException('找不到临时文件夹', 6);
break;
case UPLOAD_ERR_CANT_WRITE:
throw new upFException('文件写入失败', 7);
break;
default:
throw new upFException('未知类型错误', 8);
endswitch;
endif;
if ($type !== strtolower($fileType)):
throw new upFException('文件类型错误', 9);
endif;
return true;
}
catch (upFException $e)
{
echo $e;
return false;
}
}
public function saveFile($destDir,$destFileName)
{
$tmp = $this->tmpFileName;
$ori = $this->oriFileName;
$dest = $destDir.$destFileName;
if(is_uploaded_file($tmp))://判断是否是post方式上传的文件
move_uploaded_file($tmp,$dest);
endif;
}
}
}
?>
case 'regist':
if($_SERVER['REQUEST_METHOD']==='POST'):
$name = trim($_POST['userName']);
$nc = trim($_POST['userNc']);
$pwd = md5(trim($_POST['pwd1']));
$tpwd = trim($_POST['pwd1']);
$rdate = date('Y-m-d');
//使用用户名生成文件头像
$fileName = strstr($name,'.',true).'.png';
//生成一个文件上传的对象
$file = new UploadFile($_FILES['userHeadImg']);
//检测文件是否上传成功,参数是文件上传的类型限定
if($file->checkSuccess('image')):
//如果文件上传成功,则保存文件到服务器上
$destDir = $_SERVER['DOCUMENT_ROOT']. '/php11/0511/images/headImg/';
$file->saveFile($destDir,$fileName);
else:
exit('<script>alert("头像上传失败");location.href="register.php";</script>');
endif;
$data = ['name'=>"$name",'nc'=>"$nc",'password'=>"$pwd",'tpassword'=>"$tpwd",'regdate'=>"$rdate",'headimg'=>"$fileName"];
//先判断一下用户名是否已经注册
$where = "`name`='$name'";
$res = $user->select($table,$where);
if(count($res)):
exit('<script>alert("邮箱已经注册过了,可直接登录");location.href="login.php";</script>');
else:
$rowCount = $user->insert($table,$data); //返回受影响的记录条数
if($rowCount):
exit('<script>alert("注册成功");location.href="login.php";</script>');
else:
exit('<script>alert("注册失败");location.href="register.php";</script>');
endif;
endif;
else:
die('请求类型错误!');
endif;
- 实现效果
![](https://img.php.cn/upload/image/728/202/332/1589495813682026.png)
![](https://img.php.cn/upload/image/155/354/400/1589495827190727.png)
2.文件批量上传类 UploadMulFile.php
<?php
namespace compotents\conn
{
include 'upFException.php';
class UploadMulFile
{
private $oriFileName = [];//原始文件名
private $fileType = [];//文件类型
private $error = [];//错误类型
private $tmpFileName = [];//临时文件名
private $fileSize = [];//已上传文件大小
public function __construct($file)
{
$this->oriFileName = $file['name'];
$this->fileType = $file['type'];
$this->error = $file['error'];
$this->tmpFileName = $file['tmp_name'];
$this->fileSize = $file['size'];
}
public function checkSuccess($fileType):bool//检测文件是否上传成功
{
$errors = $this->error;
foreach($errors as $key => $error ):
$type = strstr($this->fileType[$key],'/',true);
$ori = $this->oriFileName[$key];
try {
if ($error > UPLOAD_ERR_OK) :
switch ($error) :
case UPLOAD_ERR_INI_SIZE:
throw new upFException($ori.'上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值', 1);
break;
case UPLOAD_ERR_FORM_SIZE:
throw new upFException($ori.'上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值', 2);
break;
case UPLOAD_ERR_PARTIAL:
throw new upFException($ori.'文件只有部分被上传', 3);
break;
case UPLOAD_ERR_NO_FILE:
throw new upFException($ori.'没有文件被上传', 4);
break;
case UPLOAD_ERR_NO_TMP_DIR:
throw new upFException($ori.'找不到临时文件夹', 6);
break;
case UPLOAD_ERR_CANT_WRITE:
throw new upFException($ori.'文件写入失败', 7);
break;
default:
throw new upFException($ori.'未知类型错误', 8);
endswitch;
endif;
if ($type !== strtolower($fileType)):
throw new upFException($ori.'文件类型错误', 9);
endif;
}
catch (upFException $e)
{
echo $e;
return false;
}
endforeach;
return true;//如果没有错误,返回true
}
public function saveFile($destDir):array
{
$tmps = $this->tmpFileName;
$images = [];
foreach($tmps as $key => $tmp):
$tmp = $this->tmpFileName[$key];
$ori = $this->oriFileName[$key];
$images[$key] = $ori;
$dest = $destDir.$ori;
if(is_uploaded_file($tmp))://判断是否是post方式上传的文件
move_uploaded_file($tmp,$dest);
endif;
endforeach;
return $images;
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/form.css">
<title>Document</title>
</head>
<body>
<div class="showgoods">
<?php
require 'autoLoad.php';
use compotents\conn\UploadMulFile;
if(count($_FILES)):
$file = new UploadMulFile($_FILES['goods']);
if($file->checkSuccess('image')):
//如果文件上传成功,则保存文件到服务器上
$destDir = $_SERVER['DOCUMENT_ROOT']. '/php11/0511/images/goods/';
$images = $file->saveFile($destDir,$fileName);
endif;
?>
<div style="display: flex;flex-flow: row wrap;justify-content: space-evenly;
align-items: center;">
<?php foreach($images as $image):?>
<div
style="width: 180px;height:150px; display:flex;justify-content:cetner;align-items: center;margin: 10px 10px;">
<img src="images/goods/<?php echo $image ?>" alt=""></div>
<?php endforeach; ?>
</div>
<?php
else:
?>
<form action="" method="POST" enctype="multipart/form-data">
<div>
<input type="file" name="goods[]" multiple>
</div>
<div><button type="submit">上传</button></div>
</form>
<?php
endif;
?>
</div>
</body>
</html>
- 代码效果图
![](https://img.php.cn/upload/image/947/816/811/1589495944559897.png)
![](https://img.php.cn/upload/image/648/619/195/1589495956717417.png)
3.文件上传异常类 upFException.php
<?
namespace compotents\conn
{
use Exception;
class upFException extends Exception
{
// 在异常子类中,可以访问并重写Exception中的四个属性,通过__toString()格式化异常输出信息
public function __toString()
{
return <<< UPLOAD
<style>
table {border-collapse: collapse;border:1px solid black;text-align: center;}
td {border:1px solid black;padding: 5px;}
tr:first-of-type {background-color:#eee;
}
tr:last-of-type td {color: coral;}
</style>
<table>
<tr><td>代码</td><td>信息</td><td>文件</td><td>行号</td></tr>
<tr><td>$this->code</td><td>$this->message</td><td>$this->file</td><td>$this->line</td></tr>
</table>
UPLOAD;
}
}
}
?>