首页 > 解决方案 > PHP-MySQL:多文件上传代码中的第一个文件未上传到服务器

问题描述

我正在尝试将多个图像上传到服务器和 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;
?>

谁能确定是什么问题?

标签: phpmysql

解决方案


您正在计算一个不存在的属性。您正在计算 $FILES 中“文件”的“名称”。$FILES 是一个可能包含数组的关联数组。在您的情况下,“文件”是一个数组。所以试着计算一下。

$total = count($FILES["files"])

推荐阅读