File upload is a very common feature nowadays . Every second web application has this feature implemented in it .Javascript made it too handy to upload files using it’s tons pre-built libraries .
But why to load a whole library and make your website slower just for a single functionality which can be handled using vanilla javascript fetch() API ( modern version of XHR used for sending request ) .
In this I’m going to demonstrate you how you can upload files using javascript’s in-built fetch() API.
Steps to upload files using fetch() API are as follows :
Get File Data
First of all make an input of file type
<input type = 'file' id = 'file_to_upload' />
Now whenever user selects a file we need to trigger an event
//select the file input tag
var file = document.getElementById('file_to_upload');
//add event listener
file.addEventListener('change', () => {
uploadFile(file.files[0]);
});
In the above code uploadFile()
is user-defined function we define it later . This function will recieve a object of file in the form of parameter and upload the file on backend server using fetch()
API .
Now let’s define the uploadFile() function
function uploadFile(file){
//validating file before upload
if(isValid(file)){
// if file is valid
//making a formData object and appending file to it
const fd = new FormData();
fd.append('file_to_upload',file);
//uploading file
fetch('https://example.com/uploadFile',{
method : 'POST',
body : fd
})
.then(response => response.json())
.then(data => console.log(data));
}else{
//if file is not valid
console.log('file size if greater then 2mb');
}
}
Validate File
isValid()
is a user-defined function to validate file size and check if image is png , jpg , jpeg or not , if image is greater than 2mb or having different file format then it will throw an error . Let’s implement the isValid()
function .
function isValid(file){
// check file type
if(!['image/jpeg', 'image/jpg', 'image/png'].includes(file.type)) {
return false;
}
// check file size (< 2MB)
if(file.size > 2 * 1024 * 1024) {
return false;
}
}
Handling File Upload on Backend Using PHP
Now if you are a PHP programmer then here is the code snippet of handling file upload using PHP on server side .
<?php
if (isset($_FILES['file_to_upload'])) {
// get details of the uploaded file
$fileTmpPath = $_FILES['file_to_upload']['tmp_name'];
$fileName = $_FILES['file_to_upload']['name'];
$fileSize = $_FILES['file_to_upload']['size'];
$fileType = $_FILES['file_to_upload']['type'];
$fileNameCmps = explode(".", $fileName);
$fileExtension = strtolower(end($fileNameCmps));
//making a new file name before storing on server
$newFileName = md5(time() . $fileName) . '.' . $fileExtension;
// directory in which the uploaded file will be moved
$uploadFileDir = './uploaded_files/';
$dest_path = $uploadFileDir . $newFileName;
if(move_uploaded_file($fileTmpPath, $dest_path)){
$message ='File is successfully uploaded.';
echo $message;
}else{
$message = 'There was some error';
echo $message;
}
}
?>
That’s how you can upload file using fetch() API and handle it on server side using PHP.
You can follow me on Linkedin : Anand Raj
Don’t forget to follow our Linkedin page for latest updates : BePractical
Next Article : Javascript asynchronous programming with XMLHttpRequest() method
Thank you for reading ✌