Uploading multiple files using html5 and php

2019-02-24 04:57发布

I have a file upload form set up with the HTML5 multiple attribute.

However, the form still only uploads a single file. Do i need to create some sort of a looping function in the php or is there another way of doing this?

Here's my code...

form:

<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post" enctype="multipart/form-data">        
       <input type="file" multiple="multiple" name="file[]" id="file" />
       <input name="submit" type="submit" value="Submit" />    
</form>

php:

<?php
if(isset($_POST['submit'])) {           
foreach($_FILES['newsImage'] as $file){ 
if ((($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg")))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {


    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
}
}
?>

4条回答
2楼-- · 2019-02-24 05:21

I believe this code could serve the purpose. It loops through the $_FILES array and creates an array with key => value pair of all the attributes for for each file.

$temp = array();
foreach ($_FILES['file'] as $key => $value) {
    foreach($value as $index => $val){
        $temp[$index][$key] = $val;
    }
}
查看更多
时光不老,我们不散
3楼-- · 2019-02-24 05:24
<?php   

    include 'db.php';

      extract($_POST);

        extract($_POST);
        if(isset($submit))
        {

          $count = count($_FILES['image']['name']);

           for($i=0;$i<$count;$i++)
           {
              $fname = $_FILES['image']['name'][$i];
              $file_tmp = $_FILES['image']['tmp_name'][$i];
              $file_size =  $_FILES['image']['size'][$i];
               $file_type=$_FILES['image']['type'][$i];
               echo $file_size,$file_type;         
               $target = "img/".$fname;
               move_uploaded_file($file_tmp,$target);
                echo "uploaded succ !"."<br>";

           }

        }

?>
查看更多
Root(大扎)
4楼-- · 2019-02-24 05:26

I believe your field should be <input type="file" multiple="multiple" name="files[]" />

And then in PHP:

<?php
   foreach($_FILES['files'] as $file){
       // Handle one of the uploads
   }
?>
查看更多
家丑人穷心不美
5楼-- · 2019-02-24 05:39
for ($i = 0; $i < count($_FILES['newsImage']['name']); $i++) {
    // handle upload
}
查看更多
登录 后发表回答