我正在尝试将多个图像上传到服务器和mysql数据库,但是多个图像中的第一个图像没有被上传。
我遍历选定的文件,并尝试在for循环中上载每个图像。除了第一张图片,所有图片都可以正确上传。
这是我用来选择多个文件的html:
<form action="imageUpload.php" method="post" enctype="multipart/form-data">
Select Image File to Upload:
<input type="file" name="files[]" multiple>
<input type="submit" name="submit" value="Upload">
我的php代码如下:
<?php
include("php/db.php");
$statusMsg = '';
// Count # of uploaded files in array
$total = count($_FILES["files"]["name"]);
// File upload path
$targetDir = "productImages/";
if(isset($_POST["submit"]) && !empty($_FILES["files"]["name"]))
{
for( $i=0 ; $i < $total ; $i++ )
{
// Allow certain file formats
$allowTypes = array('JPG','jpg','png','jpeg','gif');
$fileName = basename($_FILES["files"]["name"][$i]);
$targetFilePath = $targetDir . $fileName;
$fileType = strtolower(pathinfo($targetFilePath,PATHINFO_EXTENSION));
if(in_array($fileType, $allowTypes))
{
// upload file to temporary location
if (is_uploaded_file($_FILES["files"]["tmp_name"][$i]))
{
// Upload file to server
if(move_uploaded_file($_FILES["files"]["tmp_name"][$i], $targetFilePath))
{
// Insert image file name into database
$insertSQL = "INSERT into images (file_name, uploaded_on) VALUES ('".$fileName."', NOW())";
if(openConnection())
{
$insert = insertQuery($insertSQL);
}
closeConnection();
if($insert){
$statusMsg = "The file ".$fileName. " has been uploaded successfully.";
}else{
$statusMsg = "File upload failed, please try again.";
}
}
else
{
$statusMsg = "Sorry, there was an error uploading your file.";
}
}
else
{
$statusMsg = "Sorry, file could not upload to temp location.";
}
}
else
{
$statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF files are allowed to upload.';
}
}
}else{
$statusMsg = 'Please select a file to upload.';
}
echo "<br>" . $statusMsg;
?>
任何人都可以找出问题所在吗?
答案 0 :(得分:0)
您正在计算不存在的属性。您正在计算$ FILES中“文件”的“名称”。 $ FILES是一个可能包含数组的关联数组。在您的情况下,“文件”是一个数组。因此,请尝试算一下。
$total = count($FILES["files"])
答案 1 :(得分:0)
我发现了问题。问题不在于代码,而在于我的XAMPP的“ php.ini”文件。我尝试上传的文件大于2MB,而“ php.ini”文件中可以上传的最大文件大小为2MB。
我点击了以下链接,以在php.ini文件中设置以下字段:
upload_max_filesize = 200M
post_max_size = 201M