php - 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;
?>
谁能确定是什么问题?
解决方案
您正在计算一个不存在的属性。您正在计算 $FILES 中“文件”的“名称”。$FILES 是一个可能包含数组的关联数组。在您的情况下,“文件”是一个数组。所以试着计算一下。
$total = count($FILES["files"])
推荐阅读
- ios - Google 日历 API iOS 快速入门
- c++ - 如何在 C++ 中读取输入字符串,忽略空格
- tensorflow - 通过云 TPU 的 host_call_fn() 生成梯度摘要?
- r - 可以将 readLines 用于 R 的 ngram 处理吗?
- javascript - 我需要显示 i var n = d.getTimezoneOffset(); 的结果 在 javascript 中的 PHP 回显命令中
- wordpress - Woocommerce:管理订单列表 - 预览 - 重命名底部按钮
- python - 将字典中的数据转换为行
- php - 通过AJAX在PHP中插入数组数据
- javascript - 如果文件在一行中有多个使用管道(|)fs模块分隔的数据,如何读取文本文件?
- python - 将过滤器应用于 plt.imshow 时出现轴缩放问题