How to Upload an Image Using jQuery and JavaScript

Last updated 1 month ago | 41 views 75     5

Tags:- HTML JQuery PHP

Uploading an image using jQuery and JavaScript can enhance user experience by providing a smooth and interactive process. Here’s a step-by-step guide to achieve this.

✅ Step 1: Create the HTML Form

This form allows users to select an image file for upload.

<form id="uploadForm" enctype="multipart/form-data">
    <input type="file" name="image" id="imageInput" accept="image/*">
    <button type="submit">Upload Image</button>
</form>
<div id="preview"></div>
  • enctype="multipart/form-data": Required for file uploads.

  • accept="image/*": Restricts selection to image files.

  • #preview: Displays a preview of the uploaded image.

✅ Step 2: Handle the File Selection with jQuery

$(document).ready(function() {
    $('#imageInput').on('change', function(event) {
        const file = event.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                $('#preview').html(`<img src="${e.target.result}" alt="Image Preview" width="200">`);
            };
            reader.readAsDataURL(file);
        }
    });

    $('#uploadForm').on('submit', function(event) {
        event.preventDefault();
        const formData = new FormData(this);

        $.ajax({
            url: 'upload.php',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            success: function(response) {
                alert('Image uploaded successfully!');
            },
            error: function() {
                alert('Image upload failed.');
            }
        });
    });
});
  • FileReader(): Reads the file and converts it to a data URL for preview.

  • FormData(): Handles the form data for the AJAX request.

  • $.ajax(): Sends the file to the server for processing.

✅ Step 3: Server-Side Script (upload.php)

if ($_FILES['image']['error'] === UPLOAD_ERR_OK) {
    $uploadDir = 'uploads/';
    $uploadFile = $uploadDir . basename($_FILES['image']['name']);

    if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadFile)) {
        echo 'Image uploaded successfully';
    } else {
        echo 'Failed to upload image';
    }
} else {
    echo 'Error during file upload';
}
  • $_FILES['image']: Accesses the uploaded file.

  • move_uploaded_file(): Moves the file to the desired directory.

✅ Step 4: Set Proper Directory Permissions

Ensure the uploads directory is writable:

chmod 777 uploads

Conclusion

With this method, you can efficiently upload an image using jQuery and JavaScript, providing a preview and handling server-side storage. This approach improves user experience and allows better handling of image uploads.