PHP图片文件批量上传
示例:
<?php
error_reporting(E_ALL);
//printf('<pre>%s</pre>',print_r($_FILES,true));
class UploadException extends EXception
{
public function __toString()
{
return <<< UPLOAD
<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>
<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>
UPLOAD;
}
}
try {
foreach($_FILES as $file){
foreach($_FILES['ufile']['error'] as $k=>$v)
{
$ufiles=['name'=>$_FILES['ufile']['name'][$k],
'type'=>$_FILES['ufile']['type'][$k],
'tmp_name'=>$_FILES['ufile']['tmp_name'][$k],
'error'=>$_FILES['ufile']['error'][$k],
'size'=>$_FILES['ufile']['size'][$k]
];
if($ufiles['error']=== 0)
{
$fileType =$ufiles['type'] ?? null;
//判断类型
$type = strstr($fileType,'/',true);//对文件类型进行切割。加上true取/前面的
if(!is_null($fileType))
{
echo $type;
if($type !== 'image') throw new UploadException('文件类型错误',8);
}
//判断临时文件
$tmplFileName = $ufiles['tmp_name'] ?? NULL; //临时文件名
//1.首先临时文件是存在的并且必须是通过POST上传的
// 2.将文件从临时目录移动到目标目录中:uploads
//move_uploaded_file(临时文件,目标文件)
if($tmplFileName && is_uploaded_file($tmplFileName))
{
$originFileName = $ufiles['name'] ?? null;
//获取上传的文件名
$newFileName = strstr($originFileName,'.');
//分割获取文件的后缀如:.jpg/.png/.gif/...
$destFileName = 'uploads/'.md5(time().mt_rand(1,100)).$newFileName ?? null;
//生成存储图片的地址$destFileName
//destFileName 设置上传文件的地址
//如果move_uploaded_file执行成功
if(move_uploaded_file($tmplFileName, $destFileName ))
{
echo '<p>'. $ufiles['name'].'上传成功';
//预览图片
echo "<img src='{$destFileName}' width=200>";
}
else
{
echo '上传失败';
}
}
}
else
{
$errorCode = $ufiles['error'] ?? null;
// 使用系统常量进行判断
if ($errorCode > UPLOAD_ERR_OK)
{
switch($errorCode)
{
case UPLOAD_ERR_INI_SIZE:
throw new UploadException('文件超过`php.ini`中`upload_max_filesize`值',1);
break;
case UPLOAD_ERR_FORM_SIZE:
throw new UploadException('文件大小超过表单中`MAX_FILE_SIZE`指定的值',2);
break;
case UPLOAD_ERR_PARTIAL:
throw new UploadException('文件只有部分被上传',3);
break;
case UPLOAD_ERR_NO_FILE:
throw new UploadException('没有文件被上传',4);
break;
case UPLOAD_ERR_NO_TMP_DIR:
throw new UploadException('找不到临时文件夹',5);
break;
case UPLOAD_ERR_CANT_WRITE:
throw new UploadException('文件写入失败',6);
break;
default:
throw new UploadException('未知错误',7);
}
}
}
}
}
}
catch (UploadException $e) {
echo $e;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>多文件上传</title>
</head>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<fieldset>
<legend>多文件上传</legend>
<!-- <input type="hidden" name="MAX_FILE_SIZE" value="500000"> -->
<!-- MAX_FILE_SIZE 设置上传文件的大小 -->
<input type="file" name="ufile[]" id ="ufile" multiple="multiple">
<button>上传</button>
</fieldset>
</form>
</body>
</html>
示例图: