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.