介绍
简单的记录下如何处理解决使用PHP处理前端上传的多图处理功能,本文只贴了图片处理的方法,其余文件类型也是差不多的。各位道友可自行修改处理代码,都是八九不离十。文末也放了代码,可自行下载学习。
代码部分
html代码部分,input的name属性my_file
后面加了一个中括号[]
,就是以数组形式上传,后端PHP接收到的数据就更好的以数组形式接收处理。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片上传</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<p> <input type="file" name="my_file[]" multiple></p>
<button>提交</button>
</p>
</form>
</body>
</html>
PHP后端代码部分,可以根据自己的项目需求适当修改,这边只作保存image
类型的图片文件描述。
<?php
printf('<pre>%s</pre>', print_r($_FILES, true));
$res = upload($_FILES);
printf('<pre>%s</pre>', print_r($res, true));
// 单
// print_r(uploadFile($_FILES));
// 多
print_r(uploadFile($res));
function uploadFile(array $files, $uploadPath = 'uploads/storage'): array
{
if (!file_exists($uploadPath)) {
mkdir($uploadPath, 0777, true);
}
foreach ($files as $file) {
if ($file['error'] == 0) {
// echo strstr($file['type'], '/', true);
if (strstr($file['type'], '/', true) !== 'image') {
$tips = $file['name'] . '文件类型错误';
continue;
} else {
// 确保文件名的唯一性
$targetName = $uploadPath . '/' . date('YmdHis') . md5($file['name'] . time()) . strstr($file['name'], '.');
// echo $targetName;
// 将文件从临时位置 移动到指定位置
if (!move_uploaded_file($file['tmp_name'], $targetName)) {
$tips = $file['name'] . '文件移动失败';
continue;
} else {
$img[] = $targetName;
}
}
}
}
if (!empty($tips)) {
$res['error'] = $tips;
} else {
$res['fileRealPath'] = $img;
}
return $res;
}
// 处理多文件的格式
function upload(): array
{
$i = 0;
foreach ($_FILES as $k => $file) {
// printf('<pre>%s</pre>', print_r($file, true));
foreach ($file['name'] as $k => $v) {
$files[$i]['name'] = $file['name'][$k];
$files[$i]['type'] = $file['type'][$k];
$files[$i]['tmp_name'] = $file['tmp_name'][$k];
$files[$i]['error'] = $file['error'][$k];
$files[$i]['size'] = $file['size'][$k];
$i++;
}
}
// printf('<pre>%s</pre>', print_r($files, true));
return $files;
}
预览效果
效果如下图,结果为临时文件命令移动到存储目录。
代码附件
upload.zip大小:2.14KB
已经过安全软件检测无毒,请您放心下载。
本文地址:https://www.mainblog.cn/340.html
版权声明:本文为原创文章,版权归 阁主 所有,欢迎分享本文,转载请保留出处!
免责申明:有些内容源于网络,没能联系到作者。如侵犯到你的权益请告知,我们会尽快删除相关内容。
版权声明:本文为原创文章,版权归 阁主 所有,欢迎分享本文,转载请保留出处!
免责申明:有些内容源于网络,没能联系到作者。如侵犯到你的权益请告知,我们会尽快删除相关内容。