我正在尝试通过根据序列号创建文件夹并将文件保存到其中来上传多个文件。我的代码如下:
多次上传的HTML代码:
<div class="form-inline clearfix">
<label class="col-md-5">Select A File To Upload:</label>
<div class="col-md-4">
<input type="file" name="myfile[]" id="Uploaded_file" multiple="multiple"/>
</div>
</div><br/>
多次上传的PHP代码
if (count($_FILES["myfile"]) > 0)
{
for ($i = 0; $i < count($_FILES["myfile"]["name"]); $i++)
{
foreach ($_FILES["myfile"]["error"][$i] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$structure = "Uploads/SystemConfiguration/$formno"; //FormNo is the serial number queried from the database
if (!mkdir($structure, 0777, true))
{
die('Failed to create folders...');
}
$tmp_name = $_FILES["myfile"]["tmp_name"][$i][$key];
$name = $_FILES["myfile"]["name"][$i][$key];
$target = $target .'/' .$_FILES['myfile']['name'][$i] ;
$filepath=$_FILES['myfile']['name'][$i] ;
if(move_uploaded_file($tmp_name,"$structure/$name"))
{
echo "<center>The file ". basename( $_FILES['myfile']['name'][$i]). " has been uploaded.</center>";
}
else
{
echo "No File was uploaded";
}
}
}
}
}
即使我上传了多个文件,也只会将最后一个文件保存在目录中。如何修改我的代码以便我可以上传多个文件? 感谢任何帮助:)
答案 0 :(得分:1)
这可以在HTML5中进行。示例(PHP 5.4):
<!doctype html>
<html>
<head>
<title>Test</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input type="text" name="Filename">
<input type="file" name="my_file[]" multiple>
<input type="submit" value="Upload">
</form>
<?php
if (isset($_FILES['my_file'])) {
$myFile = $_FILES['my_file'];
$fileCount = count($myFile["name"]);
$Filename=$_POST['Filename'];
$structure = "Uploads/SystemConfiguration/$Filename";
if (!mkdir($structure, 0777, true))
{
die('Failed to create folders...');
}
for ($i = 0; $i < $fileCount; $i++) {
$name = $_FILES["my_file"]["name"][$i];
$tmp_name=$_FILES["my_file"]["tmp_name"][$i];
move_uploaded_file($tmp_name,"$structure/$name");
?>
<p>File #<?= $i+1 ?>:</p>
<p>
Name: <?= $myFile["name"][$i] ?><br>
Temporary file: <?= $myFile["tmp_name"][$i] ?><br>
Type: <?= $myFile["type"][$i] ?><br>
Size: <?= $myFile["size"][$i] ?><br>
Error: <?= $myFile["error"][$i] ?><br>
</p>
<?php
}
}
?>
</body>
</html>
以下是在文件对话框中选择2项后Chrome中的样子:
点击“上传”按钮后,这就是它的样子。
这只是一个完整工作答案的草图。有关在PHP中正确,安全地处理文件上载的详细信息,请参阅PHP Manual: Handling file uploads。