How to upload an Image to a Server using JavaScript - onlyxcodes

Thursday 6 June 2024

How to upload an Image to a Server using JavaScript

In this tutorial, you'll learn how to upload image to the server using JavaScript


One of the most popular files handling tasks in a web application is uploading a file and parsing it in the backend.


To perform the file upload from our local machine to the web server, there are a variety of JavaScript libraries present.


For uploading files, in this tutorial, I did not use the jQuery library or the $.ajax() function.


In this post, I used pure vanilla JavaScript for file uploading to the server using PHP script without refreshing the page, utilizing XMLHttpRequest Ajax's request.


javascript upload file to server

Table Content

1. Create Database And Table

2. Configure Database Connection

3. Create HTML Form for File Uploading

4. Implement JavaScript Code

5. PHP Script (Server)

6. Testing Application


1. Create Database And Table

I have assumed you have installed the localhost server like XAMPP or WAMP Server in your system to use PhpMyAdmin.


Establish a database with any name in the PhpMyAdmin and select it, then use the SQL command below to successfully create a file name table.


CREATE TABLE `tbl_file` (
  `id` int(11) NOT NULL,
  `image` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

2. Configure Database Connection

The dbconfig.php file is located here. I used the PDO extension to create the MySQL database connection in this file.


<?php

$db_host="localhost"; 
$db_user="root";	
$db_password="";	
$db_name="javascript_file_upload_db";	

try
{
	$db=new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_password);
	$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOEXCEPTION $e)
{
	$e->getMessage();
}

?>

3. Create HTML Form for File Uploading

Look at this file, which is the index.html file for the client-side file uploading form.


I have created an HTML form inside this file that clients will view when they want to upload the file.


On the front end, the user can select a file from their system using the <input type="file">.


Look at the last upload button; it has the saveFile() function, which we'll use to upload selected files to the PHP script using JavaScript. This approach uses the onclick method to handle the click event.


After closing the form tag, you'll see that a span tag is available. The id property value of this span tag displays a client-side file upload success message from the server or PHP script.


On the client side, the id attribute value of this span element also displays file uploading suitable error messages from the server or PHP script.


<form id="fileupload_form" class="form-horizontal">
					
	<div class="form-group">
	<label class="col-sm-3 control-label">Select File</label>
	<div class="col-sm-6">
	<input type="file" id="myfile" class="form-control"/>
	</div>
	</div>
				
	<div class="form-group">
	<div class="col-sm-offset-3 col-sm-6 m-t-15">
	<input type="button" onclick="saveFile();" value="Upload" class="btn btn-success btn-lg btn-block"> 
	</div>
	</div>
			
</form>
			
<span id="message_box" class="col-sm-offset-3 col-sm-6 m-t-15"></span>

I used the Bootstrap package to create this form.


file upload form - javascript upload file client side - file upload javascript library - html file upload example - how to save uploaded file in folder using javascript - html upload file

4. Implement JavaScript Code

The pure Vanilla JavaScript code starts after the </html> tag in the index.html file is closed.


When users click the upload button after choosing a file, the JavaScript below calls the saveFile() function, and the XMLHttpRequest (or Ajax) process sends the selecting file request to the "upload.php" server file and receives a response without reloading the page.


If the PHP (or server) script response is successful, a file uploaded successfully message will be displayed; otherwise, the appropriate file uploading error messages will be displayed.


<script>

function saveFile()
{	
	var fl = document.getElementById("myfile").files;
	
	if(fl.length > 0)
	{
		var fd = new FormData();
		
		fd.append("file", fl[0]);

		var xhr = new XMLHttpRequest();

		xhr.open('POST', 'upload.php', true);
		
		xhr.send(fd);
		
		xhr.onreadystatechange = function()
		{
			if(xhr.readyState == 4 && xhr.status == 200)
			{
				var response = JSON.parse(xhr.responseText);
				
				document.getElementById('fileupload_form').reset();
				
				if(response.success)
				{
					document.getElementById('message_box').innerHTML = response.success;
				}
				else if(response.size_error)
				{
					document.getElementById('message_box').innerHTML = response.size_error;
				}
				else if(response.exists_error)
				{
					document.getElementById('message_box').innerHTML = response.exists_error;
				}
				else if(response.extension_error)
				{
					document.getElementById('message_box').innerHTML = response.extension_error;
				}
			}
		};
	}
	else
	{
		alert('Please Select File !!');
	}
}
	
</script>

Explanation:


Row no 5 –  To start, use the document.getElementById() function to access the selected file.


The id attribute value of the <input type="file"> tag is "myfile." This value is pasted into the document.getElementsById() method, and this method collects file properties and stores them in the fl object.


var fl = document.getElementById("myfile").files;

Row no 7 – If the condition checks that the specified file length is greater than zero, it will continue.


if(fl.length > 0)
{

Row no 9 – I created the FormData interface to store the given file request before sending it to the server. The FormData interface's object is the fd.


var fd = new FormData();

Row no 11 – Using the append() method, I added the selected file to the fd object's 'file' key.


fd.append("file", fl[0]);

Row no 13 to 17 – To send an Ajax request, I created an XMLHttpRequest object. The xhr indicates the object.


The open() method takes three arguments, two of which are required and the third of which is optional, but I also pass the third argument, true.


The first input is an HTTP POST request that transports selected file requests, and the second parameter is the URL for the PHP file "upload.php" which we'll create next.


Paste the FormData object of fd into the send() method and this method will make an Ajax call.


var xhr = new XMLHttpRequest();

xhr.open('POST', 'upload.php', true);
		
xhr.send(fd);

Row no 19 – Create a function called onreadystatechange that responds to changes in the server response. The onreadystatechange function is a callbacks function. When the status of the request changes, this callback function is called.


xhr.onreadystatechange = function()
{

Row no 21 – Take note of the other characteristics of the XMLHttpRequest object.


For starters, the readyState element specifies the present state of our request. Its value varies from 0 to 4 depending on how long the AJAX request takes. The value 4 indicates, for example, that we have access to the response data.


Second, the status element tells whether the request was successful or not; for example, the value 200 shows a successful request.


if(xhr.readyState == 4 && xhr.status == 200)
{

Row no 23 – Because PHP to Javascript responses is in JSON string format, we must transform (parse) them to Javascript objects and arrays.


var response = JSON.parse(xhr.responseText);

Row no 25 – The id property value of the form is used by the reset() method to reset the form. The form's id attribute value is fileupload_form. The value of the form id attribute is returned by the document.getElementById() method.


document.getElementById('fileupload_form').reset();

Note: Within the span tag, which is placed after closing the form tag, the innerHTML attribute displays the server's response.


The id property value of the span tag is message_box.


Row no 27 to 30 –  The response is successful if the conditions are met. If yes, the message "File uploaded successfully" will appear.


Here is the response.success, The PHP script returns a JSON string as success.


if(response.success)
{
	document.getElementById('message_box').innerHTML = response.success;
}

Row no 31 to 34 – else if the condition checks the response will return a file size error. If this is the return, the error message "file size is too large" will appear.


Here is the response.size_error, The PHP script returns a JSON string called size_error.


else if(response.size_error)
{
	document.getElementById('message_box').innerHTML = response.size_error;
}

Row no 35 to 38 – else if the condition checks the response contains an error message stating that the file already exists. If this error message appears once, the error message for a file that already exists will be displayed.


Here is the response.exists_error, The PHP script returns a JSON string called exists_error.


else if(response.exists_error)
{
	document.getElementById('message_box').innerHTML = response.exists_error;
}

Row no 39 to 42 – else if the condition checks the response will provide a file extension error message. If this error is caused then it will display the specified file extensions are allowed like jpg, jpeg, png, doc, pdf.


Here is the response.extension_error, The PHP script returns a JSON string called extension_error.


else if(response.extension_error)
{
	document.getElementById('message_box').innerHTML = response.extension_error;
}

Row no 46 to 49 – If the user does not select a file, the else condition renders the alert() method to display the please select file error message.


else
{
	alert('Please Select File !!');
}

5. PHP Script (Server)

As a server, we're using PHP.


The upload.php file is available here. This file handles the Ajax (XMLHttpRequest) request. This file only contains PHP file upload code and runs in the background silently.


This file receives and validates file requests sent via the HTTP POST method.


If all goes well, this file will upload a new file, save it in the upload folder, store the file name in the database, and respond to JavaScript with a file uploaded successfully message.


<?php 

require_once "dbconfig.php";

if(isset($_FILES['file']['name']))
{	

	$fileName = $_FILES['file']['name'];
	$tempPath = $_FILES['file']['tmp_name'];
	$fileSize = $_FILES['file']['size'];

	$upload_path = 'upload/';	
	
	$fileExt = strtolower(pathinfo($fileName,PATHINFO_EXTENSION)); // get image extension
	
	$valid_extensions = array('jpeg', 'jpg', 'png', 'pdf', 'doc', 'docx', 'ppt', 'xls');
	
	if(in_array($fileExt, $valid_extensions))
	{				
		//check file not exist our upload folder path
		if(!file_exists($upload_path . $fileName))
		{
			// check file size '5MB'
			if($fileSize < 5000000)
			{
				if(move_uploaded_file($tempPath, $upload_path . $fileName)) // move file from system temporary path to our upload folder path 
				{
					$statement=$db->prepare('INSERT INTO tbl_file(image) VALUES (:file)');
		
					$statement->bindParam(':file',$fileName);
		 		
					$statement->execute(); 	

					$success = '<div class="alert alert-success"><button type="button" class="close" data-dismiss="alert">&times;</button> 
									File Uploaded Successfully  
								</div>';
							
					echo json_encode(array('success' => $success));	
				}					
			}
			else
			{		
				$sizeError = '<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert">&times;</button> 
									Sorry, your file is too large, please upload 5 MB size  
							  </div>';
							  
				echo json_encode(array('size_error' => $sizeError));				 
			}
		}
		else
		{		
			$existsError = '<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert">&times;</button> 
								Sorry, file already exists check upload folder  
					        </div>';
							
			echo json_encode(array('exists_error' => $existsError));				 
		}
	}
	else
	{				
		$extensionError = '<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert">&times;</button> 
								Sorry, only JPG, JPEG, PNG, Doc, Docx files are allowed  
						   </div>';
						   
		echo json_encode(array('extension_error' => $extensionError));				 
	}
}

Explanation:


Row no 3 – I added the connection (dbconfig.php) file to the database using the require_once function. I used the database object $db to do a PDO insert query.


require_once "dbconfig.php";

Row no 5 to 10 – If condition, obtains submitted file request key “file” and kept in the PHP superglobal array $_FILES [ ]. The isset() function set this key properly.


This array contains the name, type, size, and temporary name of your uploaded file.


$fileName = $_FILES['file']['name'] – The original name of the file is determined by this array value.


$tempPath = $_FILES['file']['tmp_name'] – It array is used to obtain the temporary location that is uploaded to the file. Make a note of this information and use it to relocate the uploaded file to our folder's location.


$fileSize = $_FILES['file']['size'] – his value of the array determines the file size in bytes.


if(isset($_FILES['file']['name']))
{	

	$fileName = $_FILES['file']['name'];
	$tempPath = $_FILES['file']['tmp_name'];
	$fileSize = $_FILES['file']['size'];

Row no 12 – I created the $upload_path variable and saved the path to the upload folder on the server where the file will be saved.


$upload_path = 'upload/';

Row no 14 – This code gets information about a file path and saves it to the variable $fileExt.


The pathinfo() function returns information about a file's path. PATHINFO_EXTENSION just returns the extension.


All characters in a string are lowercased using the strtolower() method.


$fileExt = strtolower(pathinfo($fileName,PATHINFO_EXTENSION)); // get image extension

Row no 16 – I created an array with the valid image extensions jpeg, jpg, png, doc, docx, ppt, and xls using the array() function. The variable $valid_extensions is set to this array.


$valid_extensions = array('jpeg', 'jpg', 'png', 'pdf', 'doc', 'docx', 'ppt', 'xls');

Row no 18 – if the condition checks, you can enable valid file formats.


Recognize this,


in_array($fileExt, $valid_extensions)


The in_array() function receives the $fileExt and $valid_extensions parameters.


The $fileExt variable was given file information, such as the name, as mentioned in the code for Row no 14.


The $valid_extensions variable contains the array values jpeg, jpg, png, doc, docx, ppt, and xls, which we described earlier in Row no 16 code.


The in_array() function first looks for file information in the $fileExt variable, then searches the $valid_extensions array for the file extension values jpeg, jpg, png, doc, docx, ppt, and xls.


if(in_array($fileExt, $valid_extensions))
{

Row no 21 – The file_exists() function is used to check whether or not a file has already existed on the server.


//check file not exist our upload folder path
if(!file_exists($upload_path . $fileName))
{

Row no 24 – The file size must be at least 5 MB if the condition check is valid.


// check file size '5MB'
if($fileSize < 5000000)
{

Row no 26 to 39 – If the condition, the move_uploaded_file() function will move the file from the temporary location to the upload folder path and save it if the above conditions are met.


In prepare() statements, PDO inserts query is used.


The bindParam() function binds the variable :file value's place in the query. That value is stored in the variable $fileName.


Finally, the execute() function runs the statement and successfully shows the file upload message in the bootstrap alert-success box. And we store this message in the $success variable.


The response key for transmitting to JavaScript is "success."


The $success variable stores this response key.


The "success" key and $success variable must be put in the json_encode() function, which includes the array() function, for this key response to be sent in JSON format.


if(move_uploaded_file($tempPath, $upload_path . $fileName)) // move file from system temporary path to our upload folder path 
{
	$statement=$db->prepare('INSERT INTO tbl_file(image) VALUES (:file)');
		
	$statement->bindParam(':file',$fileName);
		 		
	$statement->execute(); 	

	$success = '<div class="alert alert-success"><button type="button" class="close" data-dismiss="alert">&times;</button> 
					File Uploaded Successfully  
				</div>';
							
	echo json_encode(array('success' => $success));	
}

Row no 41 to 48 – Show the selected file a large error message with the connected bootstrap alert error box if this else condition is caused. This error message appears when users select a file larger than 5MB in size.


The response key for transmitting to JavaScript is "size_error."


The $sizeError variable holds this response key.


The "size_error" key and $sizeError variable are kept in the json_encode() function, which contains the array() function, and must be supplied in JSON format.


else
{		
	$sizeError = '<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert">&times;</button> 
						Sorry, your file is too large, please upload 5 MB size  
				  </div>';
							  
	echo json_encode(array('size_error' => $sizeError));				 
}

Row no 50 to 57 – This condition will display an error message that the selected file already exists, along with a bootstrap alert error box. This error message appears when a user picks a file that already exists in our save folder.


The response key for transmitting to JavaScript is "exists_error."


The $existsError keeps this response key.


The "exists_error" key and $existsError variable are stored in the json_encode() function, which involves the array() function, and must be supplied in JSON format.


else
{		
	$existsError = '<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert">&times;</button> 
						Sorry, file already exists check upload folder  
			        </div>';
							
	echo json_encode(array('exists_error' => $existsError));				 
}

Row no 59 to 66 – With the associated bootstrap alert error box, the condition will display the selected file extension error message. This error message appears when a user picks a file that does not match our extensions, such as jpg, jpeg, png, pdf, doc, docx, ppt, and xls.


The response key for forwarding to JavaScript is "extension_error."


The $extensionError keeps track of this response key.


The "extension_error" key and $extensionError variable are placed in the json_encode() method, which has the array() function, and must be delivered in JSON format.


else
{				
	$extensionError = '<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert">&times;</button> 
							Sorry, only JPG, JPEG, PNG, Doc, Docx files are allowed  
					   </div>';
						   
	echo json_encode(array('extension_error' => $extensionError));				 
}

6. Testing Application

Click the Upload button after selecting the file you want to upload. Once the file upload is complete, it will display a success message as shown below.


Once the file upload is complete, it will display a success message as shown below.

An error will appear if you select a file type that isn't included in the condition, such as video or audio, as shown below.


An error will appear if you select a file type that isn't included in the condition,

If you choose a file that has already exists, you will see an error message similar to the one below.


If you choose a file that has already exists, you will see an error message similar to the one below.

Download Codes

No comments:

Post a Comment

Post Bottom Ad