Easy Ajax Image Upload and view with JQuery, PHP

Today, we will look on how to upload an image with specific extensions into a server using AJAX and PHP. In this project, we will be using AJAX to show the user the uploaded image without refreshing the page. Also, we will be using extension validation using PHP in run time while uploading in order to prevent unknown file formats.

Overview

In order to build an image uploader, we will need to create the below-specified file with the specified code saved in it. Group all the files in the same folder.

  • Index.php
  • Ajaxhandling.php
  • Script.js
  • Jquery min library

Index.php

The index file contains the HTML code which shows the file upload form as well as the file browser and the submit button .
Basically, it is the user end where a user performs the upload.

<!doctype html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>Tutorial-17</title>
<link rel="stylesheet" href="style.css" type="text/css" />
<script type="text/javascript" src="js/jquery-1.11.3-jquery.min.js"></script>
<script type="text/javascript" src="js/Script.js"></script>
</head>
<body>
<div class="container">
<h1><a href="">Image Upload Section</a></h1>
<hr>
<div id="preview"><img src="no-image.jpg" /></div>

<form id="form" action="ajaxhandling.php" method="post" enctype="multipart/form-data">
<input id="uploadImage" type="file" accept="image/*" name="image" />
<input id="button" type="submit" value="Upload">
</form>
<div id="err"></div>
<hr>
</div>
</body>
</html>

Ajaxhandling.php

This file contains all the allowed extension arrays as well as the storing path of images in the server. When images are selected and submit button is pressed it will send the image to this code segment. It will first extract the image into a variable and then pass the image trough extension array in order to validate the file extension of an image. Then if all options are validated it will finally move the file from the temporary location to specified location on the server.

<?php

$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp'); // allowed file extensions
$path = 'uploads/'; // file upload directory

if(isset($_FILES['image']))
{
$img = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];

// get uploaded file's extension
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));

// can upload same image using rand function
$final_image = rand(1000,1000000).$img;

// check's valid format
if(in_array($ext, $valid_extensions))
{
$path = $path.strtolower($final_image);

if(move_uploaded_file($tmp,$path))
{
echo "<img src='$path' />";
}
}
else
{
echo 'invalid file';
}
}

?>

Script.js

The Javascript file is used to make the ajax asynchronous call to ajaxhandling.php file as well as with ajax library. we use fadeIn element code block to show users the uploaded image without refreshing the page and if there is any error in uploading, a message is printed saying invalid upload.

$(document).ready(function (e) {
$("#form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "ajaxhandling.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend : function()
{
$("#err").fadeOut();
},
success: function(data)
{
if(data=='invalid file')
{
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
}
else
{
// view uploaded file.
$("#preview").html(data).fadeIn();
$("#form")[0].reset();
}
},
error: function(e)
{
$("#err").html(e).fadeIn();
}
});
}));
});

Download Source code and complete Working Demo:

Download the complete source code.

Grab the the free working demo Intantly!

You have Successfully Suscribed!

Leave a Reply

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