How to Upload Image File using AJAX and jQuery


This tutorial will guide you through the process of uploading an image file to a server using AJAX and jQuery. We will cover creating the HTML form, writing the JavaScript/jQuery code to handle the file upload, and provide a basic PHP example for the server-side handling.

Step 1: Create the HTML Form

First, we need to create an HTML form that allows the user to select an image file. This form will include an input element of type "file" and a button to trigger the upload process.

<form enctype="multipart/form-data">
    <input type="file" name="image"><br><br>
    <button type="button">Upload Image</button>
    <div ><div ></div></div>
    <div></div>
</form>

The enctype="multipart/form-data" attribute is crucial for handling file uploads. The progress div is optional, to show the upload progress.

Step 2: Include jQuery Library

Make sure you have included the jQuery library in your HTML page. You can either download it or use a CDN. Add this to the <head> section:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

Step 3: Write the jQuery/AJAX Code

Now, let's write the JavaScript/jQuery code to handle the file upload when the button is clicked. This code will prevent the default form submission behavior and use AJAX to send the file to the server.

$(document).ready(function() {
    $("#uploadButton").click(function() {
        var formData = new FormData();
        var file = $("#imageInput")[0].files[0];

        if (file) {
            formData.append("image", file);

            $.ajax({
                url: "upload.php", // Replace with your server-side script URL
                type: "POST",
                data: formData,
                contentType: false,
                processData: false,
                xhr: function() {
                    var xhr = new window.XMLHttpRequest();
                    xhr.upload.addEventListener("progress", function(evt) {
                        if (evt.lengthComputable) {
                            var percentComplete = evt.loaded / evt.total;
                            percentComplete = parseInt(percentComplete * 100);
                            $('#progress').show();
                            $('#progressBar').width(percentComplete + '%');
                        }
                    }, false);
                    return xhr;
                },
                success: function(response) {
                    $('#message').html(response);
                    $('#progress').hide();
                    $('#progressBar').width('0%');

                },
                error: function(jqXHR, textStatus, errorThrown) {
                    $('#message').html("Error uploading file: " + textStatus + " - " + errorThrown);
                    $('#progress').hide();
                    $('#progressBar').width('0%');
                }
            });
        } else {
            $('#message').html("Please select an image file.");
        }
    });
});

Explanation:

    FormData: Creates a FormData object to hold the file data. file = $("#imageInput")[0].files[0];: Gets the selected file. formData.append("image", file);: Appends the file to the FormData object with the name "image". $.ajax({...}): Performs the AJAX request.
      url: The URL of the server-side script to handle the upload. type: The HTTP method (POST). data: The FormData object containing the file. contentType: false: Important! Tells jQuery not to set the Content-Type header, as the browser will handle it correctly for FormData. processData: false: Important! Tells jQuery not to process the data. xhr: This section creates an XMLHttpRequest object and attaches a progress listener, allowing us to display a progress bar during the upload. success: A function to handle the successful response from the server. error: A function to handle errors during the AJAX request.

Step 4: Create the Server-Side Script (PHP Example)

Now, you need to create a server-side script (e.g., in PHP) to handle the uploaded file. This script will receive the file data and save it to the server.

<?php
if (isset($_FILES["image"])) {
    $target_dir = "uploads/"; // Directory where you want to save the files
    $target_file = $target_dir . basename($_FILES["image"]["name"]);
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

    // Check if image file is a actual image or fake image
    $check = getimagesize($_FILES["image"]["tmp_name"]);
    if($check !== false) {
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }


    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }

    // Check file size
    if ($_FILES["image"]["size"] > 500000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }

    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }

    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
            echo "The file ". htmlspecialchars( basename( $_FILES["image"]["name"])). " has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
} else {
    echo "No file received.";
}
?>

Explanation:

    $_FILES["image"]: Accesses the uploaded file data. $target_dir: Specifies the directory where the file will be saved. Make sure this directory exists and is writable by the web server. Basic checks (image type, file size, etc.) are performed for security and validation. move_uploaded_file(): Moves the uploaded file from the temporary directory to the specified destination.
Important: Remember to create the "uploads" directory in the same directory as your PHP script and ensure that the web server has write permissions to this directory. For production environments, you should implement more robust security measures.

By following these steps, you should be able to successfully upload image files using AJAX and jQuery. Remember to adjust the code to fit your specific needs and implement appropriate security measures for production environments. This tutorial utilizes JQuery for easy Javascript coding and Ajax for a smooth page experience.

1 Comments

Previous Post Next Post