Are you tired of wasting time uploading files one by one? The struggle is real! Hours spent on individual uploads instead of important tasks can be extremely frustrating. But don’t worry – there’s a solution for you. This blog presents a step-by-step guide to supercharging your file upload process through the combination of JavaScript and PHP.
Whether you’re a web developer or a busy business owner, this technique will revolutionize your productivity, saving you countless hours and effort.
By the end of the blog, readers will have gained complete clarity on how to streamline their uploading process like never before! Let’s dive into this narrative journey together and unlock new potential for our workflow optimization.
Contents
- HTML Layout for File upload
- PHP Code for Handling Multiple File Upload
- Send AJAX request to File upload using JavaScript
- Output
- Conclusion
1. HTML Layout for File upload
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.
<div > <input type="file" name="files" id="files" multiple> <input type="button" id="btn_uploadfile" value="Upload" onclick="uploadFile();" > </div>
2. PHP Code for Handling Multiple File Upload
Create an ajaxfile.php
file and an uploads
folder in the project folder to store the uploaded files.
Next, define a variable called $countfiles
to keep track of the total number of files uploaded. Also, assign the desired upload location to the variable $upload_location
.
Create another variable, $count
, to store the count of successfully uploaded files. Initialize it to 0.
Implement a loop to iterate over the files being uploaded. Within each iteration, read the file name and create a corresponding file path within the uploads
folder.
Read the file extension and define an array called $valid_ext
that contains valid file extensions allowed for upload.
Check if the file extension exists in the $valid_ext
array. If it does, proceed to upload the file to the specified $upload_location
and increment the $count
variable by 1 to track the successful uploads.
Finally, return the value stored in the $count
variable, representing the total count of successfully uploaded files.
<?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. Send AJAX request to File upload using 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.
// 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
Uploading multiple files using JavaScript and PHP is a great way to optimize your workflow and boost your productivity. By making use of powerful tools like FormData and AJAX, you can establish a streamlined approach that saves both time and effort.
Whether you’re an experienced developer or just someone who wants to streamline their file-sharing process, this technique can make a real difference in the way you work. So why wait? Give it a try today and reap the benefits for yourself!
If you found this tutorial helpful then don't forget to share.