我正在尝试允许在一个表单中上传多个图像。但是它不太有效,我无法发现问题。
窗体如下所示:
<form method="post" action="add-property.php" enctype="multipart/form-data">
<input type="file" multiple="multiple" name="files[]" />
<input type="submit" name="submit" class="property-submit" value="Submit Property" />
</form>
后面的 PHP(在同一页面上)是:
//Image logic
for ($i = 0; $i < count($_FILES['files']['name']); $i++) {
if (($_FILES['files']['type'] == "image/jpeg") || ($_FILES['files']['type'] == "image/png") || ($_FILES['files']['type'] == "image/jpg")) {
if ($_FILES['files']["error"] > 0) {
echo "Return Code: ".$_FILES['files']["error"]."<br />";
}
else {
$target = $_SERVER['DOCUMENT_ROOT'].'/images/property-images/';
if (file_exists($target.$currUser.$_FILES['files']['name'])) {
echo $file["name"] . "already exists.";
}
else {
move_uploaded_file($_FILES['files']["tmp_name"],
$target.$currUser.$_FILES['files']["name"]);
echo "Stored in: ".$target.$currUser.$_FILES['files']["name"];
}
}
}
else {
echo 'error';
}
}
$currUser是用户的当前用户名。
问题是 - 当我尝试上传文件时。什么也没发生。它回显错误,但文件类型绝对正确。不会将任何图像发送到该文件夹。我哪里会出错?
编辑 - 请求的 var 转储:
array(1) {
["files"]=>
array(5) {
["name"]=>
array(1) {
[0]=>
string(17) "Chrysanthemum.jpg"
}
["type"]=>
array(1) {
[0]=>
string(10) "image/jpeg"
}
["tmp_name"]=>
array(1) {
[0]=>
string(14) "/tmp/php1WEAjj"
}
["error"]=>
array(1) {
[0]=>
int(0)
}
["size"]=>
array(1) {
[0]=>
int(879394)
}
}
}
排除count($_FILES['files']['name'])
,您需要为每个$_FILES
引用添加[$i]
,例如$_FILES['files']["tmp_name"][$i]
。
另外,$file["name"]
应该是$_FILES['files']["name"][$i]
的。
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {
if (($_FILES['file']['type'][$i] == "image/jpeg") || ($_FILES['file']['type'][$i] == "image/png") || ($_FILES['file']['type'][$i] == "image/jpg")) {
if ($_FILES['file']["error"][$i] > 0) {
echo "Return Code: ".$_FILES['file']["error"][$i]."<br />";
}
else {
if (file_exists("upload/".$_FILES['file']['name'][$i])) {
echo $_FILES['file']["name"][$i] . "already exists.<br>";
}
else {
move_uploaded_file($_FILES['file']["tmp_name"][$i],
"upload/".$_FILES['file']["name"][$i]);
echo "Stored in: ". "upload/" .$_FILES['file']["name"][$i];
}
}
}
else {
echo 'error';
}
}