我正在尝试将多个文件上传到一个目录。我“编写”的代码适用于一个文件,但是当我尝试上传多个文件时它不起作用。我试图确定故障在哪里,我相信它与计数有关。尽管当我尝试回显正在计算多少文件时,无论我选择了多少文件,我总是得到“1”。我知道这仅适用于一个文件,因为我返回的变量始终为“1”,因此仅适用于一个文件。
收集我正在使用带有 post 方法 html 的 html 表单的文件:
<form id="upload" action="upload.php" method="POST" enctype="multipart/form-data">
<fieldset>
<legend>HTML File Upload</legend>
<input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="300000" />
<div>
<label for="fileselect">Files to upload:</label>
<input type="file" id="fileselect" name="fileselect[]" multiple="multiple" />
<div id="filedrag">or drop files here</div>
</div>
<div id="submit">
<button type="submit">Upload Files</button>
</div>
</fieldset>
</form>
我使用的 javascript 启用了拖放功能,来自: http ://www.sitepoint.com/html5-file-drag-and-drop/
罪魁祸首PHP:
if(isset($_FILES['fileselect']['tmp_name'])) {
// Number of uploaded files
$num_files = count($_FILES['fileselect']['tmp_name']);
echo $num_files;
/** loop through the array of files ***/
for($i=0; $i <= $num_files;$i++) {
// check if there is a file in the array
if(!is_uploaded_file($_FILES['fileselect']['tmp_name'][$i])) {
$messages[] = 'No file uploaded';
}
else {
$unique = substr(number_format(time() * rand(),0,'',''),0,10);
$newImg = "img".$unique;
$filename = basename($_FILES['file']['name'][$i]);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
//$new = md5($filename).'.'.$extension;
$the_file_type = $_FILES['fileselect']['type'][$i];
$the_file_size = $_FILES['fileselect']['size'][$i] / 1024;
$the_file_name = $_FILES['fileselect']['name'][$i];
$ok=1;
//This is our size condition
if ($uploaded_size > 350000) {
$messages[] = "Your file is too large.<br>";
$ok=0;
}
//This is our limit file type condition
if ($uploaded_type =="text/php") {
$messages[] = "No PHP files<br>";
$ok=0;
}
//Here we check that $ok was not set to 0 by an error
if ($ok==0) {
$messages[] = "Sorry your file was not uploaded";
}
//If everything is ok we try to upload it
else {
if(move_uploaded_file($_FILES['fileselect']['tmp_name'][$i], "uploads/{$newImg}")) {
echo "The file ". basename( $_FILES['uploadedfile']['name'][$i]). " has been uploaded";
echo "<br />";
//echo $the_file_type;
//echo "<br />";
//echo $unique;
//echo "<span>schmeckle!</span>";
//echo "<br />";
//echo $the_file_size;
//echo "<br />";
//echo $the_file_name;
$insertSQL = "INSERT INTO interviews_media_images SET ";
$insertSQL .= "fileType='$the_file_type', ";
$insertSQL .= "fileRef='$newImg', ";
$insertSQL .= "fileSize='$the_file_size', ";
$insertSQL .= "fileName='$the_file_name' ";
echo $insertSQL;
//mysql_query( $insertSQL);
//echo mysql_error();
} else {
$messages[] = "Sorry, there was a problem uploading your file.";
}
}
}
}
}