Preview Image before upload using Jquery and PHP

preview-image-before-upload-jquery-php-featured
preview-image-before-upload-jquery-php-blog

Preview Image before upload using Jquery and PHP:

Image uploading is basic mandatory functionality in any applications where we need to upload user/customer profile pictures.

But manytimes there is a chance to upload the wrong image by mistake if we do not have the option to preview it before uploading.

To put dot to this issue, we are sharing the tutorial on how to preview the image before uploading using jquery in php.

demo
download

We have also shared the PHP source code here to move the uploaded image file to server path.

We can upload the gif,png and jpg files. We have used bootstrap to make the colorful UI.

Required Imports:

We have imported bootstrap library files also for better UI, but only jQuery is enough to implement the preview before image upload, so do importing below js and css files based on your need,

<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.11.0/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/redmond/jquery-ui.css" type="text/css" />
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" type="text/css" />

 

jQuery Form to select the image:

<div class="row">
	<div class="col-sm-8">
		<label>Select Image to Upload</label>
		<div class="row">
			<div class="col-sm-6"><form id="selected_image" action="" method="post" enctype="multipart/form-data"><input type="file" name="image_file" id="image_file" class="btn btn-sm btn-primary" style="width:250px;"/></div>
				<div class="col-sm-6"><input type="submit" value="Upload" class="btn btn-sm btn-success" style="width:250px;"/></div>
			</div>
		</div>
		<div class="col-sm-4">
			<div class="img"><img id="img_preview" /></div>
		</form></div>
</div>

The above code is to select the image file which you need to upload. Once the browse button clicked and selected the image, then the below .change(function(e)) will be triggered inside this function, we will check the image format (should be gif/jpg/jpeg/png) and using filereader we are previewing the image. Image properties like width/height can be customized as your wish in the previewImg method.

Script:

$(document).ready(function (event) {
// triggered when the form submitted
$("#selected_image").on('submit',(function(event) {
event.preventDefault();
$("#upload_status").empty();
$.ajax({
// URL to move the uploaded image file to server
url: "Preview_Upload.php",
// Request type
type: "POST",
// To send the full form data
data: new FormData(this),
contentType: false,
processData:false,
// UI response after the file upload
success: function(data)
{
$("#upload_status").html(data);
}
});
}));

// Triggered when the image changed (browse)
$(function() {
$("#image_file").change(function(event) {
if(-1!=$.inArray($("#image_file")[0].files[0].type, ["image/jpeg","image/png","image/jpg","image/gif"])){
var populateImg = new FileReader();
populateImg.onload = previewImg;
populateImg.readAsDataURL($("#image_file")[0].files[0]);
}
});
});

// Function to show the image as a preview
function previewImg(event) {
$('.img').css("display", "block");
$('#img_preview').attr('src', event.target.result);
$('#img_preview').attr('width', '300px');
$('#img_preview').attr('height', '250px');
};
});

 PHP moving file to server code:

move_uploaded_file($source, $destination) will return the true/false. Based on the response you can identify the file upload status.

$isMoved = move_uploaded_file($tempPath,$destFullPath) ;
// $tempPath - Source upload file temporary path
// $destFullPath - Destination folder name where the file need to be moved.

index.php Full Source code:

<!doctype html>
<html lang="en">
	<head>
		<title>Image Preview before Upload Demo - Javadomain.in</title>
		<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
		<script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
		<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.11.0/jquery-ui.min.js"></script>
		<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/redmond/jquery-ui.css" type="text/css" />
		<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" type="text/css" />
		<script type="text/javascript">
$(document).ready(function (event) {
// triggered when the form submitted
$("#selected_image").on('submit',(function(event) {
event.preventDefault();
$("#upload_status").empty();
$.ajax({
// URL to move the uploaded image file to server
url: "Preview_Upload.php",
// Request type
type: "POST",
// To send the full form data
data: new FormData(this),
contentType: false,
processData:false,
// UI response after the file upload
success: function(data)
{
$("#upload_status").html(data);
}
});
}));

// Triggered when the image changed (browse)
$(function() {
$("#image_file").change(function(event) {
if(-1!=$.inArray($("#image_file")[0].files[0].type, ["image/jpeg","image/png","image/jpg","image/gif"])){
var populateImg = new FileReader();
populateImg.onload = previewImg;
populateImg.readAsDataURL($("#image_file")[0].files[0]);
}
});
});

// Function to show the image as a preview
function previewImg(event) {
$('.img').css("display", "block");
$('#img_preview').attr('src', event.target.result);
$('#img_preview').attr('width', '300px');
$('#img_preview').attr('height', '250px');
};
});
		</script>
	</head>
	<body>
		<div class="container">
			<div class="row">
				<div class="span12">
					<div class="head">
						<div class="row-fluid">
							<div class="span12">
								<div class="span6">
									<h1 class="muted"><a href="www.ngdeveloper.com">&nbsp;&nbsp;&nbsp;Image Preview before Upload Demo | Javadomain.in</a></h1>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>

			<div class="jumbotron">
				<div class="container">
					<div class="row">
						<div class="col-sm-8">
							<label>Select Image to Upload</label>
							<div class="row">
								<div class="col-sm-6"><form id="selected_image" action="" method="post" enctype="multipart/form-data"><input type="file" name="image_file" id="image_file" class="btn btn-sm btn-primary" style="width:250px;"/></div>
									<div class="col-sm-6"><input type="submit" value="Upload" class="btn btn-sm btn-success" style="width:250px;"/></div>
								</div>
							</div>
							<div class="col-sm-4">
								<div class="img"><img id="img_preview" /></div>
							</form></div>
					</div>
					<div id="upload_status"></div>
				</div>
			</div>
		</div>
	</div>
</body>
</html>

Full Source code of Preview_Upload.php file:

Do not forget to create the uploads folder in the path where you placed your index.php/Preview_Upload.php.

<?php
if(isset($_FILES["image_file"]["type"]))
{
$uploadedImgFileExtension = $_FILES["image_file"]["type"];
$uploadedImgFileSize = $_FILES["image_file"]["size"];
// checking the image file types and size
if(( ($uploadedImgFileExtension=="image/png") || ($uploadedImgFileExtension=="image/gif") || ($uploadedImgFileExtension=="image/jpg") || ($uploadedImgFileExtension=="image/jpeg")) && ($uploadedImgFileSize < 100000)) {
// Name of the uploaded file
$uploadedImgFileName =$_FILES['image_file']['name'];
if (file_exists("upload/" . $uploadedImgFileName)) {
echo $uploadedImgFileName . " Exists already ";
}
else
{
// Temporary path to store the uploaded image
$tempPath = $_FILES['image_file']['tmp_name'];
// destination folder name where the uploaded image need to be moved
$moveFileTo = "upload/";
$destFullPath = $moveFileTo.$uploadedImgFileName;
// Moving the uploaded image file
$isMoved = move_uploaded_file($tempPath,$destFullPath) ;
if ($isMoved == true) {
echo "Image Uploaded Successfully";
echo "<br/><b>Name:</b> " . $uploadedImgFileName . "<br>";
echo "<b>Type:</b> " . $uploadedImgFileExtension . "<br>";
echo "<b>Size:</b> " . ($uploadedImgFileSize / 1024) . " kB<br>";
} else {
echo "ERROR: File not moved correctly";
}
}
}
else
{
echo "Invalid Image File";
}
}
?>

Screenshots:

Image Preview:

Image Preview

Image Uploaded:

Image uploaded successfully

Leave a Reply