Mostly the server-side scripting language such as PHP is used to upload file to the server. With this method, an HTML form is submitted to upload the selected file to the server. To provide a better user interface, we can use client-side technology such as jQuery Ajax to upload files without page refresh. Moreover, you can use simple JavaScript to upload files to the server.
The JavaScript FormData interface provides an easy way to construct key/value pairs with form fields and send them to the server side using the XMLHttpRequest method. This technique can be used to upload files to the server with JavaScript. In this tutorial, we will show you how to upload multiple files using JavaScript.
In this example, we will use the FormData object to post file data to server-side script with JavaScript and upload multiple files to the server using PHP.
HTML Code:
Create <input> elements with type="file"
to let the user select files.
fileValidation
) in onchange event.UploadFiles
) in the onclick event. <div class="wrapper">
<!-- Status message -->
<div id="status-msg"></div>
<!-- File upload form -->
<div class="form-group">
<label>Select Files:</label>
<input type="file" class="form-control" id="file_input" onchange="return fileValidation()" multiple>
</div>
<button id="uploadBtn" class="btn btn-primary" onclick="UploadFiles()">Upload</button>
</div>
JavaScript Code:
1. The fileValidation()
function handles the file size and type validation process.
allowedExtensions
variable that are allowed to be uploaded. It will check the type of the selected files and restrict if any file is selected other than the allowed file types.allowedTotalSize
variable that is allowed to be uploaded. It will validate the combined size of all select files and make sure not exceed the allowed size.2. The UploadFiles()
function handles the multiple file upload with JavaScript.
formData.append()
method.upload_init.php
) using the fetch()
method.<script>
//File type and size validation handler function
function fileValidation(){
let allowedExtensions = /(\.jpg|\.jpeg|\.png|\.pdf)$/i;
let allowedTotalSize = 20; //in MB
const fileInput = document.getElementById('file_input');
let fileInput_length = fileInput.files.length;
let fileSize = 0;
if (fileInput_length > 0) {
for (var i = 0; i < fileInput_length; i++) {
fileSize = fileSize+fileInput.files[i].size;
if(!allowedExtensions.exec(fileInput.files[i].name)){
alert('Please upload file having extensions .jpeg/.jpg/.png/.pdf only.');
fileInput.value = '';
return false;
}
}
let fileSize_mb = (fileSize / 1024 / 1024).toFixed(2);
if(fileSize_mb > allowedTotalSize) {
alert('The combined size of all files should not exceed '+allowedTotalSize+' MB.');
fileInput.value = '';
return false;
}
}
}
// Multiple files upload handler function
function UploadFiles(){
const fileInput = document.getElementById('file_input');
let fileInput_length = fileInput.files.length;
const formData = new FormData();
if (fileInput_length > 0) {
for (var i = 0; i < fileInput_length; i++) {
formData.append("files[]", fileInput.files[i]);
}
}
const messageContainer = document.querySelector("#status-msg");
messageContainer.innerHTML = '';
const btnContainer = document.querySelector("#uploadBtn");
btnContainer.disabled = true;
btnContainer.innnerHTML = 'Uploading...';
fetch("upload_init.php", {
method: "POST",
body: formData
})
.then(response => response.json())
.then(data => {
if (data.status == 1) {
messageContainer.innerHTML = '<div class="alert alert-success">'+data.msg+'</div>';
} else {
messageContainer.innerHTML = '<div class="alert alert-danger">'+data.error+'</div>';
}
btnContainer.disabled = false;
btnContainer.innnerHTML = 'Upload';
setTimeout(function () {
messageContainer.innerHTML = "";
}, 5000);
})
.catch(console.error);
}
</script>
This file is loaded by the fetch() method (from the client side) to perform the multiple file upload using PHP.
$allowTypes
– The file types that are allowed to be uploaded.$uploadDir
– Folder path where the files will be stored on the server.<?php
$allowTypes = array('jpg','png','jpeg','pdf');
$uploadDir = 'uploads/';
if(!empty($_FILES['files']['name'])){
$uploaded_files_str = '';
foreach($_FILES['files']['name'] as $key=>$val){
// File upload path
$fileName = basename($_FILES['files']['name'][$key]);
$targetFilePath = $uploadDir.$fileName;
// Check whether file type is valid
$fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
if(in_array($fileType, $allowTypes)){
// Upload file to server
if(move_uploaded_file($_FILES['files']["tmp_name"][$key], $targetFilePath)){
$uploaded_files_str .= $fileName.', ';
}
}
}
$uploaded_files_str = trim($uploaded_files_str, ', ');
$output = [
'status' => 1,
'msg' => 'Files have been uploaded successfully!<br/>Uploaded Files: {'.$uploaded_files_str.'}'
];
echo json_encode($output);
}else{
echo json_encode(['status' => 0, 'error' => 'Please select files to upload!']);
}
?>
Ajax File Upload with Form Data using PHP
Here we demonstrate a simple method to upload multiple files with JavaScript. You don’t need any third-party dependancy such as jQuery to upload files to the server. Allow the user to upload multiple images or files without page refresh using JavaScript. This example provides a user-friendly way to upload multiple files to the server with JavaScript using PHP. You can also enhance the functionality of this JavaScript multiple file upload script as needed.
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request