在php中的一个输入文件上将多个图像上传到服务器

时间:2018-04-13 01:39:53

标签: php server image-uploading image-upload

我试图在一个输入上将多个图像上传到服务器(点击按钮),我有以下代码用于index.html:

 <!DOCTYPE html>
    <html>
    <head>

    </head>
    <body>
      <form id="contact" action="upload.php" method="post" enctype="multipart/form-data" >
    <!-- image 1 -->
      <label class="aa">
       Upload an image
        </label>
          <div>
           <input name="Field26"  type="file" size="12"  data-file-max-size="10"  tabindex="1"  required  />
          </div><br>
    <!-- image 2 -->
      <label class="bb">
       Upload an image
        </label>
          <div>
            <input name="Field33"  type="file" size="12"  data-file-max-size="10"  tabindex="2"  required  />
      </div>  
      </br>
      <button name="submit" type="submit" value="Upload Image" data-submit="...Sending">Upload</button>

     </form>
    </div>
    </body>
    </html>

我有以下upload.php代码用于上传一张图片:

<?php
$dirCheck = 'images/$_POST[project]';
if (file_exists($dirCheck)){
    echo "Sorry, directory already exists.";
    $uploadOk = 0;
}else{
    mkdir("images/$_POST[project]",0777,true);
    echo "The new folder $_POST[project] has been created.</br>";
    $uploadOk = 1;
}

$target_dir = "images/$_POST[project]/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ". ";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
?>

如何更改代码以上传多张图片?谢谢!

1 个答案:

答案 0 :(得分:0)

您必须在name属性中使用数组:

<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="fileupload[]" /><br><br>
    <input type="file" name="fileupload[]" /><br><br>
    <input type="file" name="fileupload[]" /><br><br>

    <input type="submit" name="submit" value="SAVE"/>
</form>

或者您可以使用多个属性:

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

然后在PHP中使用:

foreach($_FILES['fileupload'] as $file) {
    ....
}