How to upload multiple files with JavaScript and PHP
Adding multiple file elements for uploading multiple files is time-consuming and you need to write some extra code for this.
You can do it with a single file element by enabling multiple file selection.
Read the selected files and append in the FormData object for passing to the AJAX file for upload.
In this tutorial, I show how you can upload multiple files with JavaScript and PHP.
1. HTML
Create a file and button element. To enable multiple file selection add multiple
attribute in the file element.
Added onclick
event on the button which calls uploadFile()
function.
Completed Code
<div >
<input type="file" name="files" id="files" multiple>
<input type="button" id="btn_uploadfile"
value="Upload"
onclick="uploadFile();" >
</div>
2. PHP
Create an ajaxfile.php
file and an uploads
folder to store files.
Count total files and assign to $countfiles
. Assign upload location to $upload_location
.
Create count
variable to store the number of files successfully uploaded.
Loop on the files. Read the file name and create a file path.
Read file extension and assign valid file extensions to $valid_ext
Array.
If file extension exists in the $valid_ext
Array then upload the file and increment $count
by 1.
Return $count
.
Completed Code
<?php
// Count total files
$countfiles = count($_FILES['files']['name']);
// Upload directory
$upload_location = "uploads/";
$count = 0;
for($i=0;$i < $countfiles;$i++){
// File name
$filename = $_FILES['files']['name'][$i];
// File path
$path = $upload_location.$filename;
// file extension
$file_extension = pathinfo($path, PATHINFO_EXTENSION);
$file_extension = strtolower($file_extension);
// Valid file extensions
$valid_ext = array("pdf","doc","docx","jpg","png","jpeg");
// Check extension
if(in_array($file_extension,$valid_ext)){
// Upload file
if(move_uploaded_file($_FILES['files']['tmp_name'][$i],$path)){
$count += 1;
}
}
}
echo $count;
exit;
3. JavaScript
Create uploadFile()
function which calls on button click.
Assign the total number of selected files in totalfiles
variable. If totalfiles
is not greater than 0 than alert("Please select a file");
.
If totalfiles > 0
then create FormData
object and loop on the selected files and append in the FormData
object.
To send AJAX request create an object of XMLHttpRequest
. With open()
method set request method to "POST"
and AJAX file path.
Handle AJAX successful callback with onreadystatechange()
method. Assign this.responseText
to response
variable and alert the response
.
Pass formData
object with send()
method.
Completed Code
// Upload file
function uploadFile() {
var totalfiles = document.getElementById('files').files.length;
if(totalfiles > 0 ){
var formData = new FormData();
// Read selected files
for (var index = 0; index < totalfiles; index++) {
formData.append("files[]", document.getElementById('files').files[index]);
}
var xhttp = new XMLHttpRequest();
// Set POST method and ajax file path
xhttp.open("POST", "ajaxfile.php", true);
// call on request changes state
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = this.responseText;
alert(response + " File uploaded.");
}
};
// Send request with data
xhttp.send(formData);
}else{
alert("Please select a file");
}
}
4. Output
5. Conclusion
Loop on the selected files and append it to the FormData object to send multiple files for upload.
0 Response to "How to upload multiple files with JavaScript and PHP"
Post a Comment