![](/img/trans.png)
[英]Ajax file upload gets only first file in filelist array for uploading
[英]PHP Multi file upload only first image uploading
我正在使用以下文件輸入的多個實例上傳圖像:
<input type="file" name="photos[]">
我已經設置了表單屬性,如下所示:
<form action="?action=form" method="post" class="nice" enctype="multipart/form-data">
當我遍歷文件數組時,我可以打印出多個文件名。
但是,一旦我嘗試上傳文件,它只會上傳陣列中的第一個文件。
這是我的PHP:
$uploadDir = '/uploads/';
$getCurrentTimeStamp = date('m-d-Y_h.i.s', time());
// Set the allowed file extensions
$fileTypes = array('jpg', 'jpeg', 'png', 'gif'); // Allowed file extensions
$theIds = $_POST["id"];
function findexts ($filename)
{
$filename = strtolower($filename) ;
$exts = split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}
//This applies the function to our file
$fileCount = 1;
foreach ($_FILES["photos"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$ext = findexts ($_FILES['photos']['name'][$key]) ;
if (!empty($_FILES)) {
$tempFile = $_FILES['photos']['tmp_name'][$key];
$uploadDir = $_SERVER['DOCUMENT_ROOT'] . $uploadDir;
$targetFile = $uploadDir . "equipment_photo_" .$theIds . "_".$fileCount."_". $getCurrentTimeStamp."." .$ext;
$theFileNameToStore = "equipment_photo_" .$theIds . "_".$fileCount."_". $getCurrentTimeStamp."." .$ext;
// Validate the filetype
$fileParts = pathinfo($_FILES['photos']['name'][$key]);
if (in_array(strtolower($fileParts['extension']), $fileTypes)) {
// Save the file
move_uploaded_file($tempFile,$targetFile);
echo $theFileNameToStore;
} else {
// The file type wasn't allowed
echo 'Invalid file type.';
}
}
}
$fileCount ++;
}
任何想法,為什么多個圖像將回顯,但文件無法上傳?
為了使您的生活更輕松,建議您使用此功能對$_FILES
全局變量重新排序
function rotate_array($source_array, $keep_keys = TRUE)
{
$new_array = array();
foreach ($source_array as $key => $value)
{
$value = ($keep_keys === TRUE) ? $value : array_values($value);
foreach ($value as $k => $v)
{
$new_array[$k][$key] = $v;
}
}
return $new_array;
}
然后在您的代碼中使用它:
$fileCount = 1;
$files = rotate_array($_FILES['photos']);
foreach ($files as $file) {
if (is_uploaded_file($file['tmp_name'])) {
$ext = findexts($file['name']);
$tempFile = $file['tmp_name'];
$uploadDir = $_SERVER['DOCUMENT_ROOT'] . $uploadDir;
$theFileNameToStore = "equipment_photo_" .$theIds . "_".$fileCount."_". $getCurrentTimeStamp."." .$ext;
$targetFile = $uploadDir . $theFileNameToStore;
// Validate the filetype
$fileParts = pathinfo($file['name']);
if (in_array(strtolower($fileParts['extension']), $fileTypes)) {
// Save the file
//move_uploaded_file($tempFile,$targetFile);
// Sometimes move won't work for unknown reasons, try copying, this should work
copy($tempFile, $targetFile);
echo $theFileNameToStore;
} else {
// The file type wasn't allowed
echo 'Invalid file type.';
}
}
$fileCount ++;
}
確保你phpinfo()
顯示了正確的值max_file_uploads
, upload_max_filesize
和post_max_size
。 更改您的代碼或php.ini文件中的內容
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.