关于以单一形式上传多个文件

时间:2017-07-26 11:40:24

标签: php file-upload

我正在处理我的项目我希望上传单个表单的图像,但我有两个输入字段。我想在我提交时在两个输入字段中选择两个图像时我希望我的两个文件都存储在我向您显示我的代码的文件夹中但是使用此代码,我只获得一个图像。我想要两张我上传的图片。我的表格看起来像这样

enter image description here

Here is my code:

public function upload_creative_workshop_image($post, $files){
    //print_r($files); die;
    $allowedExts= array("jpeg", "jpg", "png", "gif");
    $temp = explode(".", $files["image1"]["name"]);
    $extension = end($temp);

    if ((($files["image1"]["type"] == "image/jpeg") //check image is mp3
    || ($files["image1"]["type"] == "image/gif") //check image is mp4
    || ($files["image1"]["type"] == "image/jpg")  //check image is jpg
    || ($files["image1"]["type"] == "image/png")) //check image is png
    && ($files["image1"]["size"]) //check if image size is below 6MB
    && in_array(trim($extension), $allowedExts)) //check the extensions also
        {
            if($files["image1"]["error"] > 0){
                echo $files["image1"]["error"];
            }
            else{
        $filename = $files["image1"]["name"];
        $upload= move_uploaded_file($files["image1"]["tmp_name"], $this->img_path.$filename);
        //print_r($upload); die;
        if($upload){
            //$this->store_image_indb($filename, $post);
                }
            }
        }else{

            echo "<h1>please upload image only</h1>";
        }
}

2 个答案:

答案 0 :(得分:0)

您可以使用多层表格数据,例如

<form method=post action='' enctype='multipart/form-data'>
<input type=file name='images[]'>

答案 1 :(得分:0)

如果你有两个不同的名字,比如'image1'和'image2',请查看以下解决方案:

您必须像下面那样运行$ _FILES数组的循环,并且必须稍微修改您的上传功能,如下所示。

<?php

if (isset($_FILES)) {
    if (COUNT($_FILES) >= 1) {
    foreach ($_FILES as $i_key => $image_file) {
        $testObject = new test();
        $testObject->upload_creative_workshop_image($image_file);
}
}
}

class test {
 function upload_creative_workshop_image($image){
    //print_r($files); die;
    $allowedExts= array("jpeg", "jpg", "png", "gif");
    $temp = explode(".", $image["name"]);
    $extension = end($temp);

    if ((($image["type"] == "image/jpeg") //check image is mp3
    || ($image["type"] == "image/gif") //check image is mp4
    || ($image["type"] == "image/jpg")  //check image is jpg
    || ($image["type"] == "image/png")) //check image is png
    && ($image["size"]) //check if image size is below 6MB
    && in_array(trim($extension), $allowedExts)) //check the extensions also
    {
        if($image["error"] > 0){
            echo $image["error"];
        }
        else{
    $filename = $image["name"];
    $upload= move_uploaded_file($image["tmp_name"], 'uploads/'.$filename);
    //print_r($upload); die;
    if($upload){
        //$this->store_image_indb($filename, $post);
            }
        }
    }else{

        echo "<h1>please upload image only</h1>";
    }
}
}
?>