使用输入文件字段上载多个图像

时间:2016-05-05 18:06:31

标签: php file-upload

我正在构建一个简单的网站,我想将图像上传到文件夹中,因此我可以通过在输入框中启用multiple来完成此操作。

这是我的HTML:

<input type="file" name="gallery[]" multiple />

这是PHP:

$id = time();
$year = date("Y");
$photo_path = "photos/$year/";
$zip_path = "sets/$year/";

$photo = $_FILES["photo"]["name"];
$gallery = $_FILES["gallery"]["name"];

move_uploaded_file($_FILES["photo"]["tmp_name"],"$photo_path" . $id . ".jpg"); // This Adds Photo To $photo_path
move_uploaded_file($_FILES["gallery"]["tmp_name"],"$zip_path"); // This Doesn't Add 5 Files To $zip_path

这会将照片添加到$photo_path文件夹中,但不会将选定的5张图片添加到$zip_path文件夹中。

我出错的任何想法?

更新

foreach ($_FILES["gallery"] as $file) {

    move_uploaded_file($_FILES["gallery"]["tmp_name"],"$zip_path");

}

2 个答案:

答案 0 :(得分:0)

您需要在循环中处理多个文件。以下是直接来自manual的示例。

$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
        $name = $_FILES["pictures"]["name"][$key];
        move_uploaded_file($tmp_name, "$uploads_dir/$name");
    }
}

答案 1 :(得分:0)

当您调用多个文件上传时,它将返回一个文件数组。你可以像下面一样迭代它:

if(count($_FILES['gallery'])) {
    foreach ($_FILES['gallery'] as $key=>$file) {

        //do your upload stuff here
        move_uploaded_file($_FILES['gallery']["tmp_name"][$key], $zip_path . time() . ".jpg");

    }
}