如何使用 HTTP POST 使用 HTML 和 PHP 选择和上传多个文件?

2022-01-09 00:00:00 http post upload php html

我有使用 <input type="file"> 上传单个文件的经验.但是,我无法一次上传多个文件.

例如,我想选择一系列图像,然后一次性将它们上传到服务器.

如果可能,最好使用单个文件输入控件.

有谁知道如何做到这一点?

解决方案

这在 PHP 中的文件上传.

I have experience doing this with single file uploads using <input type="file">. However, I am having trouble doing uploading more than one at a time.

For example, I'd like to select a series of images and then upload them to the server, all at once.

It would be great to use a single file input control, if possible.

Does anyone know how to accomplish this?

解决方案

This is possible in HTML5. Example (PHP 5.4):

<!doctype html>
<html>
    <head>
        <title>Test</title>
    </head>
    <body>
        <form method="post" enctype="multipart/form-data">
            <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"]);

                for ($i = 0; $i < $fileCount; $i++) {
                    ?>
                        <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>

Here's what it looks like in Chrome after selecting 2 items in the file dialog:

And here's what it looks like after clicking the "Upload" button.

This is just a sketch of a fully working answer. See PHP Manual: Handling file uploads for more information on proper, secure handling of file uploads in PHP.

相关文章