How to upload Image file using AJAX and jQuery

In this tutorial, I show you How to use AJAX for uploading an Image file. That lets users upload their image and see their image preview after uploading.

This type of functionality you have already seen on many websites.

When does it use?

You can use it when you don’t want to disturb user experience and show a preview of an image after file uploaded successfully.

How to upload Image file using AJAX and jQuery


Contents

  1. HTML
  2. PHP
  3. jQuery
  4. CSS

1. HTML

Creating a <form> element in that add enctype=’multipart/form-data’. For enabling browse, file creates a file element and a button which perform upload operation when its gets clicked.

For showing the preview of an uploaded image created a <img > element.

Completed Code

<div class="container">
    <h1>AJAX File upload</h1>

    <form method="post" action="" enctype="multipart/form-data" id="myform">
        <div >
            <img src="" id="img" width="100" height="100">
        </div>
        <div >
            <input type="file" id="file" name="file" />
            <input type="button" class="button" value="Upload" id="but_upload">
        </div>
    </form>
</div>

 


2. PHP

Checking uploading file is an image or not if it then uploads that file to upload folder using move_uploaded_file() function and return path of an image which is use in jQuery for showing image otherwise return 0.

Completed Code

<?php

/* Getting file name */
$filename = $_FILES['file']['name'];

/* Location */
$location = "upload/".$filename;
$uploadOk = 1;
$imageFileType = pathinfo($location,PATHINFO_EXTENSION);

// Check image format
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
 && $imageFileType != "gif" ) {
 $uploadOk = 0;
}

if($uploadOk == 0){
 echo 0;
}else{
 /* Upload file */
 if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
 echo $location;
 }else{
 echo 0;
 }
}


3. jQuery

When upload button gets clicked then perform our jQuery operations. Created a FormData object, name it fd then, select a file $('#file')[0].files[0] and store it in files variable.

Append the file with FormData object using append function and set its key to ‘file’ by this key handle file upload action.

fd.append('file',files);

Setting up our AJAX request.

Set its URL to upload.php where handling upload operation, send it with POST method. Using FormData object fd as its data and set false to contentType and processData. When AJAX request success, then check its response is 0 or not because returning file location when file upload successfully otherwise 0 from upload.php file. If it’s not 0 then, use the response as a source for image control.

Completed Code

$(document).ready(function(){

    $("#but_upload").click(function(){

        var fd = new FormData();
        var files = $('#file')[0].files[0];
        fd.append('file',files);

        $.ajax({
            url: 'upload.php',
            type: 'post',
            data: fd,
            contentType: false,
            processData: false,
            success: function(response){
                if(response != 0){
                    $("#img").attr("src",response);
                }else{
                    alert('file not uploaded');
                }
            },
        });
    });
});

2. CSS

Add border: 2px solid gray;  to file control and set the font color to black. Add padding: 10px 5px; .

/* file */
#file{
    border: 2px solid gray;
    border-radius: 3px;
    color: black;
    padding: 10px 5px;
}

Completed Code

/* Container */
.container{
    margin: 0 auto;
    border: 0px solid black;
    width: 50%;
    height: 250px;
    border-radius: 3px;
    background-color: ghostwhite;
    text-align: center;
}
.container h1{
    background-color: cornflowerblue;
    color: white;
    font-weight: normal;
    margin-top: 0px;
    padding: 15px 5px;
    text-align: center;
}

/* file */
#file{
    border: 2px solid gray;
    border-radius: 3px;
    color: black;
    padding: 10px 5px;
}

/* Button */
.button{
    border: 0px;
    background-color: deepskyblue;
    color: white;
    padding: 5px 15px;
    margin-left: 10px;
}

Related Post

Spread the love

Be First to Comment

Leave a Reply

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