In the realm of web development, the ability to upload multiple files is often required for tasks such as image galleries, document management systems, and many others. This tutorial will guide you through the process of enabling multiple file uploads using PHP and jQuery.
The HTML form serves as the interface where the files will be selected for upload. Here, we have an input field of type "file" with the "multiple" attribute set to allow for multiple file selection:
<input id="myfile" type="file" name="myfile" multiple=multiple/>
When the "Upload" button is clicked, the sendfile() function is triggered through the onclick event handler.
The sendfile() function utilizes jQuery to construct a FormData object. This object allows for the inclusion of form data, including files, to be sent to the server-side script. Each selected file is appended to the FormData object:
for (var i = 0, len = document.getElementById('myfile').files.length; i < len; i++) { fd.append("myfile", document.getElementById('myfile').files[i]); }
On the server-side, the uploadfile.php script handles the file uploads:
<code class="php">$target = "uploadfolder/"; // for($i=0; $i <count($_FILES['myfile']['name']); $i++){ if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target.$_FILES['myfile']['name'])) { echo 'Successfully copied'; }else{ echo 'Sorry, could not copy'; } // }
However, this code is incomplete as it's missing the loop to iterate over multiple files. You would need to implement the loop as shown in the correct answer provided.
In the example provided in the answer, the jQuery code and HTML structure are similar to the incomplete code above. The key difference lies in the load.php script:
The loop has been implemented to handle multiple files.
<code class="php">foreach ($_FILES as $key) { if($key['error'] == UPLOAD_ERR_OK ){ $name = $key['name']; $temp = $key['tmp_name']; $size= ($key['size'] / 1000)."Kb"; move_uploaded_file($temp, $path . $name); echo " <div> <h1>File Name: $name</h1><br /> <h1>Size: $size</h1><br /> <hr> </div> "; }else{ echo $key['error']; } }
The above is the detailed content of How to Implement Multiple File Uploads in PHP and jQuery?. For more information, please follow other related articles on the PHP Chinese website!