<?php$imgs = [];//遍历:实现单文件/多文件上传foreach ($_FILES as $file) {// error = 0 : 表示上传成功if ($file['error'] == 0) {//判断文件类型是否正确if (strstr($file['type'], '/', true) != 'image') {$tips = '文件类型错误';continue;} else {//创建目标文件名,只要保存不重名$targetName = 'uploads/' . md5($file['name']) . strstr($file['name'], '.');//将文件从临时目录移动到目标目录if (!move_uploaded_file($file['tmp_name'], $targetName)) {$tips = '文件移动失败';} else {//将上传的目标文件名保存到一个数组,供当前页面进行预览$imgs[] = $targetName;}}}}printf('<pre>%s</pre>', print_r($imgs, true));?><!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><!--文件上传表单的属性要求1.action : 为空,表示上传到当前页面2.method : post3.enctype : multipart/form-data"--><form action="" method="post" enctype="multipart/form-data"><fieldset><legend>文件上传</legend><input type="file" name="my_pic1"><input type="file" name="my_pic2"><input type="file" name="my_pic3"><button>上传</button></fieldset></form><!-- 判断是否有错误 --><?php if (isset($tips)) : ?><!-- 显示错误 --><?= $tips ?><?php elseif (count($imgs)) : ?><!-- 预览当前图片 --><?php foreach ($imgs as $img) :?><img src="<?= $img?>" width="200"><?php endforeach;?><?php endif; ?></body></html>
<?php$imgs = [];//遍历:实现单文件/多文件上传//判断是否上传if (!isset($_FILES['my_pic'])) {$tips = '没有文件上传';} else {foreach ($_FILES['my_pic']['error'] as $key => $error) {// error = 0 : 表示上传成功if ($error == 0) {//判断文件类型是否正确$file = $_FILES['my_pic'];//根据 error 的 key 来获取对应的文件名,类型,临时文件名等if (strstr($file['type'][$key], '/', true) != 'image') {$tips = '文件类型错误';continue;} else {//创建目标文件名,只要保存不重名$targetName = 'uploads/' . md5($file['name'][$key]) . strstr($file['name'][$key], '.');//将文件从临时目录移动到目标目录if (!move_uploaded_file($file['tmp_name'][$key], $targetName)) {$tips = '文件移动失败';} else {//将上传的目标文件名保存到一个数组,供当前页面进行预览$imgs[] = $targetName;}}}}}?><!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="" method="post" enctype="multipart/form-data"><fieldset><!--多文件上传:1.name为数组:my_pic[]2.multiple 属性--><legend>文件上传</legend><input type="file" name="my_pic[]" multiple><button>上传</button></fieldset></form><!-- 判断是否有错误 --><?php if (isset($tips)) : ?><!-- 显示错误 --><?= $tips ?><?php elseif (count($imgs)) : ?><!-- 预览当前图片 --><?php foreach ($imgs as $img) : ?><img src="<?= $img ?>" width="200"><?php endforeach; ?><?php endif; ?></body></html>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号