Upload Multiple Images with Preview using jQuery Ajax and PHP

In this tutorial, you will learn how to upload multiple images with preview using ajax jQuery in PHP, and store images in the application and MySQL database.

How to Upload Multiple Images with Preview using jQuery Ajax and PHP?

Here are steps:

Step 1: Create Image Upload Form

First of all, create an index.php file and update the below HTML code into your index.php file:

<html lang="en">
<head>
<title>How to upload and display multiple images in php ajax</title>
<!-- Bootstrap Css -->
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>
<style type="text/css">
#preview img{
margin: 5px;
}
</style>
<form method='post' action='' enctype="multipart/form-data">
<input type="file" id='files' name="files[]" multiple><br>
<input type="button" id="submit" value='Upload'>
</form>
<!-- Preview -->
<div id='preview'></div>
</body>

</html>

Step 2: Add jQuery Ajax Code

Add jquery and Ajax code in the HTML file to show a preview of images before upload:

<script>
$(document).ready(function(){
$('#submit').click(function(){
var form_data = new FormData();
// Read selected files
var totalfiles = document.getElementById('files').files.length;
for (var index = 0; index < totalfiles; index++) {
form_data.append("files[]", document.getElementById('files').files[index]);
$('#preview').append("<img src='"+URL.createObjectURL(event.target.files[i])+"'>");
}
// AJAX request
$.ajax({
url: 'ajaxUpload.php',
type: 'post',
data: form_data,
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
alert("Uploaded SuccessFully");
console.log(response);
}
});
});
});
</script>

Step 3: Create Database Connection File

In this step, create a file name db.php and update the below code into your file.

<?php
	$servername='localhost';
	$username='root';
	$password='';
	$dbname = "my_db";
	$conn=mysqli_connect($servername,$username,$password,"$dbname");
	  if(!$conn){
		  die('Could not Connect MySql Server:' .mysql_error());
		}
?>

This code is used to create a MySQL database connection in your PHP project.

Step 4: Implement Code to Upload Files

Create a new file name ajaxUpload.php file and update the below code into your upload.php file.

<?php
require_once "db.php";
// Count total files
$countfiles = count($_FILES['files']['name']);
// Upload directory
$upload_location = "uploads/";
// To store uploaded files path
$files_arr = array();
// Loop all files
for($index = 0;$index < $countfiles;$index++){
   // File name
   $filename = $_FILES['files']['name'][$index];
   // Get extension
   $ext = pathinfo($filename, PATHINFO_EXTENSION);
   // Valid image extension
   $valid_ext = array("png","jpeg","jpg");
   // Check extension
   if(in_array($ext, $valid_ext)){
     // File path
     $path = $upload_location.$filename;
     // Upload file
     if(move_uploaded_file($_FILES['files']['tmp_name'][$index],$path)){
        $files_arr[] = $path;
        mysqli_query($conn,"INSERT INTO pictures (title)
		VALUES ('".$path."')");
     }
   }
}
echo json_encode($files_arr);
die;

This PHP code uploads multiple the image in the DB table and project folder.

Conclusion

In this tutorial, you have learned how to upload multiple images and display preview using jquery and ajax without a refreshing web page in PHP.

Recommended PHP Tutorials

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *