Tuesday, 29 June 2021

File Upload in JavaScript using Fetch API with PHP


In this post, you can learn How to upload file to the server using JavaScript Fetch API with PHP script which we have explained in step by step process in a very simple way.

In the web based application uploading file on to a server from web page is one of the very common and required functionality in our web application. So if you have search on internet then there are lots of JavaScript libraries are available for handle the file upload from our local computer to online server.

But for simple file upload feature, we have to use any libraries, then this upload library will increase extra load on our website and this upload feature we can easily handled by using pure vanilla JavaScript by using Fetch API. If you have not know but Fetch API is a promised based latest replacement of XHR Ajax request for making HTTP requests send to browser. So here we will use JavaScript native Fetch API for upload file on to server with PHP script.


File Upload in JavaScript using Fetch API with PHP







File Upload using Fetch


First Add the following HTML input file field to your website.


<input type="file" name="sample_image" />


Below this we have to create one division tag, and under this tag, we will display validation error or upload image file.


<div class="text-center" id="uploaded_image"></div>

After add file tag and one division tag for display output in to website, next we want to add event listner on to input file tag, which will be trigger when we have select file from local computer.


const sample_image = document.getElementsByName('sample_image')[0];

sample_image.addEventListener('change', () => {

	upload_image(sample_image.files[0]);

});


After add event listner on selecting of file and it will called upload_image() function, so we have to make upload_image() function which will upload selecting file to server with PHP script.





Validate File Type and Size before Uploading


Before uploading file on to server first we want to validate file type and file size before uploading of file. So in this example we want to upload only .jpg and .png file type image on to server and image file size mus not exceeds 2MB. So for this things we have write following javascript code.


const upload_image = (file) => {

	if(!['image/jpeg', 'image/png'].includes(file.type))
	{
		document.getElementById('uploaded_image').innerHTML = '<div class="alert alert-danger">Only .jpg and .png image are allowed</div>';

		document.getElementsByName('sample_image')[0].value = '';

		return;
	}

	if(file.size > 2 * 1024 * 1024)
	{
		document.getElementById('uploaded_image').innerHTML = '<div class="alert alert-danger">File must be less than 2 MB</div>';

		document.getElementsByName('sample_image')[0].value = '';

		return;
	}
        ............
}


Once selected file type and file size have been validated then this javascript must be prceeds for send file to server. So for send file to server here we have use FormData interface and under this we will store selected file And for send file to server here we have use JavaScript fetch() API which will send file to server and on success of image upload it will display uploaded image on web page.


const upload_image = (file) => {

	// check file type

	if(!['image/jpeg', 'image/png'].includes(file.type))
	{
		document.getElementById('uploaded_image').innerHTML = '<div class="alert alert-danger">Only .jpg and .png image are allowed</div>';

		document.getElementsByName('sample_image')[0].value = '';
		
        return;
    }

    // check file size (< 2MB)
    if(file.size > 2 * 1024 * 1024)
    {
    	document.getElementById('uploaded_image').innerHTML = '<div class="alert alert-danger">File must be less than 2 MB</div>';

    	document.getElementsByName('sample_image')[0].value = '';
        return;
    }

    const form_data = new FormData();

    form_data.append('sample_image', file);

    fetch("upload.php", {
    	method:"POST",
    	body : form_data
    }).then(function(response){
    	return response.json();
    }).then(function(responseData){

    	document.getElementById('uploaded_image').innerHTML = '<div class="alert alert-success">Image Uploaded Successfully</div> <img src="'+responseData.image_source+'" class="img-thumbnail" />';

    	document.getElementsByName('sample_image')[0].value = '';

    });

    
}


Server Side Handling File Uploading using PHP


In this example we have use PHP script for handling file upload on server side. so here we have write PHP script in upload.php file. This file will received request for upload file on to server. This script will fetch select file property from $_FILES variable and then after upload file in images folder using PHP move_uploaded_file() function.


if(isset($_FILES['sample_image']))
{

	$extension = pathinfo($_FILES['sample_image']['name'], PATHINFO_EXTENSION);

	$new_name = time() . '.' . $extension;

	move_uploaded_file($_FILES['sample_image']['tmp_name'], 'images/' . $new_name);

	$data = array(
		'image_source'		=>	'images/' . $new_name
	);

	echo json_encode($data);

}


Conclusion


So in this tutorial we have seen that Combination of FormData Object and JavaScript Fetch API are implementing our file upload task very easy way and with the help of both we can avoid reloading of whole page in order to increase our user experience. So by using Fetch API we can upload image without refresh of web page with PHP script and here we can perform HTTP request using JavaScript Fetch API and send file to server using FormData object and upload file using PHP script.

If you want to get complete source with .sql file, so please write your email address in comment box. We will send you complete source code file at your define email address.







55 comments:

  1. Replies
    1. Please check your email, we have send you source code file at your email address. thanks...

      Delete
    2. jeanmariekouekam404@gmail.com

      Delete
    3. Please check your email, we have send you source code file at your email address. thanks...

      Delete
  2. Replies
    1. Please check your email, we have send you source code file at your email address. thanks...

      Delete
  3. Replies
    1. Please check your email, we have send you source code file at your email address. thanks...

      Delete
  4. Replies
    1. Please check your email, we have send you source code file at your email address. thanks...

      Delete
  5. Replies
    1. Please check your email, we have send you source code file at your email address. thanks...

      Delete
  6. Replies
    1. Please check your email, we have send you source code file at your email address. thanks...

      Delete
  7. sandeepsinghkhalsa.0013@gmail.com

    ReplyDelete
    Replies
    1. Please check your email, we have send you source code file at your email address. thanks...

      Delete
  8. Replies
    1. Please check your email, we have send you source code file at your email address. thanks...

      Delete
  9. Replies
    1. Please check your email, we have send you source code file at your email address. thanks...

      Delete
  10. devloper.id@gmail.com

    thanks master

    ReplyDelete
    Replies
    1. Please check your email, we have send you source code file at your email address. thanks...

      Delete
  11. Replies
    1. Please check your email, we have send you source code file at your email address. thanks...

      Delete
  12. Replies
    1. Please check your email, we have send you source code file at your email address. thanks...

      Delete
  13. Replies
    1. Please check your email, we have send you source code file at your email address. thanks...

      Delete
  14. Please check your email, we have send you source code file at your email address. thanks...wayan.brati@gmail.com



    ReplyDelete
    Replies
    1. Please check your email, we have send you source code file at your email address. thanks...

      Delete
  15. Replies
    1. Please check your email, we have send you source code file at your email address. thanks...

      Delete
  16. Replies
    1. Please check your email, we have send you source code file at your email address. thanks...

      Delete
  17. Replies
    1. Please check your email, we have send you source code file at your email address. thanks...

      Delete
  18. Replies
    1. Please check your email, we have send you source code file at your email address. thanks...

      Delete
  19. Replies
    1. Please check your email, we have send you source code file at your email address. thanks...

      Delete
  20. Replies
    1. Please check your email, we have send you source code file at your email address. thanks...

      Delete
  21. Replies
    1. Please check your email, we have send you source code file at your email address. thanks...

      Delete
  22. Replies
    1. Please check your email, we have send you source code file at your email address. thanks...

      Delete
  23. Replies
    1. Please check your email, we have send you source code file at your email address. thanks...

      Delete
  24. Replies
    1. Please check your email, we have send you source code file at your email address. thanks...

      Delete
  25. I like it! please could you send me the source code? thank you!

    ReplyDelete