繁体   English   中英

用php上传多个文件

[英]Multiple file uploads with php

我正在尝试用一个表单发布上载两个文件,但是我的表单只会上载第一个文件,而不会遍历第二个文件并上载。 知道为什么吗? 我正在使用的代码如下。

<?php

$upload = $_POST['upload'];
$enteredPassword = $_POST['password'];
$uploadedFiles = $_FILES;
$password = "************";

// Where the file is going to be placed 
$target_path = "";

//interger count
$i = 0;

//upload the files
if ($upload == true && $enteredPassword == $password) {
foreach($uploadedFiles as $uploadedFile) {
    $target_path = $target_path . $uploadedFile['name'][$i]; 

    if(move_uploaded_file($uploadedFile['tmp_name'][$i], $target_path)) {
        echo "<p>The file ".  $uploadedFile['name'][$i]. 
        " has been uploaded.</p>";
    } else{
        echo "<p>There was an error uploading the {$uploadedfile['name']}, please try again!</p>";
    }
    $i++;
}
}
?>

<ul>
<form enctype="multipart/form-data" action="" method="post">
    <input type="hidden" name="upload" value="true" />
    <li>Choose a file to upload:</li>
    <li><input name="userfile[]" type="file" size="40" /></li>
    <li><input name="userfile[]" type="file" size="40" /></li>
    <li>Enter password for file upload:</li>
    <li><input name="password" type="password" size="40" /></li>
    <li><input type="submit" value="Upload File" /></li>
</form>
</ul> 

如果愿意,可以使用此插件上传多个图像。 它对我非常有用... http://www.plupload.com/example_queuewidget.php

尝试使用uploadify,它具有出色的api和回调功能,适合多次上传。 http://www.uploadify.com/

因为$ _FILES数组中只有一个元素$ _FILES [“ userfile”],所以可以预期该行为。 您可以尝试这样的事情来实现您想要的:

<?php
if(isset($_POST["submit"]))
{
    $upload = $_POST['upload'];
    $enteredPassword = $_POST['password'];
    $uploadedFiles = $_FILES["userfile"];
    $password = "12345";

    // Where the file is going to be placed 
    $base_path = "upload/";

    //upload the files
    if ($upload == true && $enteredPassword == $password) {
        foreach(array_combine($uploadedFiles["name"], $uploadedFiles["tmp_name"]) as $name => $tmp_name) {
            $target_path = $base_path .$name; 

            if(move_uploaded_file($tmp_name, $target_path)) {
                echo "<p>The file ".  $name." has been uploaded.</p>";
            }
            else
            {
                echo "<p>There was an error uploading the {$name}, please try again!</p>";
            }
        }
    }
}
?>

<ul>
<form enctype="multipart/form-data" action="" method="post">
    <input type="hidden" name="upload" value="true" />
    <li>Choose a file to upload:</li>
    <li><input name="userfile[]" type="file" /></li>
    <li><input name="userfile[]" type="file" /></li>
    <li>Enter password for file upload:</li>
    <li><input name="password" type="password" size="40" /></li>
    <li><input type="submit" name="submit" value="Upload File" /></li>
</form>
</ul> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM