How to Upload Multiple Images With Image Preview using jQuery, Ajax, and PHP
In this tutorial, I will tell you how to upload multiple images with image preview without refreshing the page using PHP, jQuery, and Ajax. You will find a very short easy and useful script here to upload.
HTML & jQuery Code
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$(document).ready(function ()
{
$('form').ajaxForm(function ()
{
alert("Uploaded SuccessFully");
});
});
function preview_image()
{
var total_file = document.getElementById("upload_file").files.length;
for (var i = 0; i < total_file; i++)
{
$('#image_preview').append("<img src='" + URL.createObjectURL(event.target.files[i]) + "'><br>");
}
}
</script>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" id="upload_file" name="upload_file[]" onchange="preview_image();" multiple/>
<input type="submit" name='submit_image' value="Upload Image"/>
</form>
<div id="image_preview"></div>
</body>
</html>
PHP Code (upload.php)
<?php
if(isset($_POST['submit_image']))
{
for ($i = 0; $i < count($_FILES["upload_file"]["name"]); $i++) {
$uploadfile = $_FILES["upload_file"]["tmp_name"][$i];
$folder = "images/";
move_uploaded_file($_FILES["upload_file"]["tmp_name"][$i], "$folder" . $_FILES["upload_file"]["name"][$i]);
}
exit();
}
?>
Leave a Reply