unknown os platform
select, preview, rename and upload image using jquery Ajax | Whats-online.info

select, preview, rename and upload image using jquery Ajax

2016:08:21 / Science and Tutorials

How to upload image to the server using Ajax jquery, preview it on the client side before uploading it to the server and, postview it after the upload using Ajax.

upload image using Jquery Ajax

You may find several tutorials, plugins demonstrating the same, but for my tutorial, it is quite different, I have tried to simplify and minimize the code to make it simple and clear to implement. Some web developers have jumped to using already build image or file uploaders which according to me I regard them difficult to configure and implement to your application. They only require a professional web designer to apply them for you. Also, some jquery AJAX uploaders are trial based, and you have an obligation to use them for a given period.

Let us get started by defining what's Ajax?
 Ajax is an asynchronous javascript and XML used to create asynchronous client based applications. It may be used on several occasions. For instance, you can build a web-based application that facilitates exchange of information across the Internet or sending and receiving data from the server without reloading the web pages.

For our tutorial, we will create our photo uploader which has a custom file chooser as shown below and also allows to select an image, check the image type, preview it on the client side before sending it to the server, and insert our image file name to the database. In case it already exists in the database, rename it by adding a random extension on the file name and then post view the image after being sent to the server. Besides, We will be using the following languages: - HTML5 for our 
form, CSS to layout our custom file input, Jquery Ajax to do image previewing, uploading, check the file type, and then send it to the server without loading our web page and then PHP to do all the SQL queries as shown in the following images.

Image 1

"Image 1" Displays the customized file input and the upload button as shown below.

Image 2

'Image 2' displays the file chooser after on change.
On file chooser change, the selected image is displayed on the client side for preview before it's sent to the server as shown below.

Image 3
'Image 3' shows the progression of the file upload. The progress icon is displayed on form submit and hides after the file has successfully  uploaded.

Image 4

'Image 4' shows a successful file submission. The div below the file name outputs the file after a successful file submission as shown below.

First, we will create our 'index.php' file that has the form which has a custom file chooser, upload button to upload our image to the server, progress icon to show the uploading process and then div to output the file name. 

Our form should have an Id, action set to null(prevent the webpage from loading). We will use post method and enctype set to multipart/form-data as shown below.

<html> <head> <title>Image Upload Jquery Ajax</title> </head> <body> <h1>Image preview,upload using jquery AJAX</h1> <form action="" id="formContent" method="post" enctype="multipart/form-data" > <div id="uploadFile"> <label for="upload" title="Upload photo"  class="camera"></label> <label for="upload" ><img  id="imageReader"></label> <input  type="file" name="file"  required id="upload"> <table> <tr> <td><button class="submitI" >Upload Image</button></td> <td><img id="uploadIm" src="load.gif"></td> </tr> <tr> <td id="type" colspan=2></td> </tr> <tr> <td  colspan=2><img id="uploadSuccess"></td> </tr> </table> </div> </form> <script src="jquery-1.10.2.js"></script> <script src="upload.js"></script> </body> </html>

For our CSS, you can either create an external stylesheet to handle the styling of the form components or internal stylesheet and include it on the head tag. The stylesheet will handle positioning of our Form and its components and customizing of our file chooser  as illustrated below.

<style> body{  width:100%; } h1{ text-align:center; background:#f0f0f0; border:1px solid black; } #uploadFile{ width:200px; margin:auto; height:auto; padding:10px; border:10px solid #f0f0f0; text-align:center; } .camera{ background:url('prof_upload.jpg');      height:150px;  width:150px;  display:block; cursor:pointer; } input[type="file"]{ display:block; width:150px; height:150px; display:none; } .submitI{ padding:5px 10px 5px 10px; background:#0000ff; color:white; width:120px; margin:auto; cursor:pointer; } #imageReader,#uploadSuccess{ max-height:150px; max-width:150px; } #uploadIm{ display:none; } </style>

Then create 'upload.js ' to handle both the change and submit function as show below.'

$(document).ready(function(){        $("#upload").change(function(){           // file on change       });         $("#formContent").submit(function(e){  // file on submit });
For our jquery Ajax file, we will be using two functions, that is, change function and submit function. Change function will we checking the file type, and previewing the image before being uploaded to the server as shown below.

.Change Function();

$("#upload").change(function(){ var file=this.files[0]; var imageFile=file.type; var match=["image/jpeg","image/png","image/jpg"]; if(!((imageFile==match[0]) || (imageFile==match[1]) || (imageFile==match[2]))){ $("#type").text("Only Jpeg/ Jpg /Png /Gif are allowed"); return false; }else{ $("#type").hide(); //alert("required"); var reader=new FileReader(); reader.onload=imageIsLoaded; reader.readAsDataURL(this.files[0]); } });    function imageIsLoaded(e){ $("#imageReader").attr('src', e.target.result);     $(".camera").hide(); $("#imgRead").show(); }

Submit function contains our formdata that includes the data type sent to the server and the $.ajax function that handles all the activities of presenting the data as shown. The Ajax function contains the Url to be handled, the data type, the content type, the cache, and a 
success function that returns a value if the data being handled has been successfully submitted.

.Submit function();

$("#formContent").submit(function(e){ e.preventDefault();      var formdata = new FormData(this); //formdata.append('file',$('#upload')[0].files[0]); $("#uploadIm").show(); $.ajax({ url: "ajax_upload_image.php", type: "POST", data: formdata, mimeTypes:"multipart/form-data", contentType: false, cache: false, processData: false, success: function(data){    alert(data); $("#uploadIm").hide(); $("#type").show().html("Image uploaded successfully<br><br>File Name:"+data);                        //document.execCommand("InsertImage", false, "upload/"+data); //alert(data); //$("#progressbar").hide(); //location.reload(); //$("#article").load("submitArticle.php"); $("#uploadSuccess").attr('src','upload/'+data); },error: function(){ alert("okey"); } }); });

Finally, create "ajax_upload_image.php" to handle posting the file to the server and inserting the filename to the database. Also, the 'connection.php' to connect and select the database as shown.


<?php $con=mysql_connect("localhost","root",""); $db=mysql_select_db("upload"); ?>


<?php require"connection.php"; $uploadImg=''; if(isset($_FILES["file"]["name"])){  $uploadImg= $_FILES["file"]["name"]; $uploadImgTmp= $_FILES["file"]["tmp_name"];  $location="upload/";  $query="select `uploadId` from `upload` where `images`='$uploadImg'";  if($query_run=mysql_query($query)){    $num_rows=mysql_num_rows($query_run);        if( $num_rows==0){   move_uploaded_file($uploadImgTmp,$location.$uploadImg);    $query="insert into `upload` values('','$uploadImg')";         if($query_run=mysql_query($query)){ echo $uploadImg; }            }else{   //move_uploaded_file($uploadImgTmp,$location.$uploadImg);   $fileData = pathinfo(basename($uploadImg));   $uploadImgC=str_replace(".","-",$uploadImg);   $fileName = $uploadImgC."-".uniqid() . '.' . $fileData['extension'];   $target_path = ($location.$fileName);    while(file_exists($target_path)){     $fileName = $uploadImgC."-".uniqid() . '.' . $fileData['extension']; $target_path = ($location.$fileName);   }  move_uploaded_file($uploadImgTmp,$target_path);     $query="insert into `upload` values('','$fileName')";         if($query_run=mysql_query($query)){ echo $fileName; }    }  }else{ echo mysql_error();  } } ?>

You can download these code from here. Unzip the file to the localhost. For the database, upload it to your local server and run the demo.

You may also like:

Leave a comment

Subscribe to get replies direct to your mailbox

Submit comment