jQuery File Upload Preview

jQuery File Upload Preview

If you want to learn, how to display the image before submitting the form by "jQuery". Thus, this post will be of great use to you. In this article, I have explained the four methods of file upload preview in jQuery. By these four methods, you can easily display the image before submitting the form by jQuery.

Image-File-Extension-Validation-In-jquery

Form Code

In this step, I have created a form using HTML, Bootstrap, and CSS for the custom design of the form.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Object</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css" rel="stylesheet"  integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9" crossorigin="anonymous">
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-lg-12 mt-4 ">
                <div class="card">
                    <div class="card-header">
                        <h1 class="text-center">Rays Coding - Preview Image Object</h1>
                    </div>
                    <div class="card-body">
                        <form action="" method="post">
                            <div class="container">
                                <div class="row">
                                    <div class="col-lg-12">
                                        <div class="mb-3">
                                            <label for="select-image" id="heading" class="form-label">Select Image</label>
                                            <input type="file" class="form-control" id="selectimage">
                                        </div>
                                    </div>
                                    <div class="col-lg-12">
                                        <div class="mb-3">
                                            <img src="product-placeholder.jpg" alt="" width="300px" height="300px" id="imageobject">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="mb-3">
                                <button type="submit" id="submit-id" class="btn">SUBMIT</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-3.7.0.slim.min.js" integrity="sha256-tG5mcZUtJsZvyKAxYLVXrmjKBVLd6VpVccqz/r4ypFE=" crossorigin="anonymous"></script>
    <script src="index.js"></script>
</body>
</html>

This HTML code sets up a webpage that allows users to preview an image before submitting a form. The page includes a Bootstrap card element with a header titled "Rays Coding - Preview Image Object". Inside the card's body, there's a form with a file input field labeled "Select Image", which users can use to choose an image file from their device.

Below the file input field, there's a tag with the ID "imageobject". Initially, it displays a placeholder image ("product-placeholder.jpg") with a width and height of 300 pixels each. This image will be replaced with the selected image when a user chooses a file using the file input field.

The form also contains a submit button labeled "SUBMIT" at the bottom, allowing users to submit the form after selecting an image.

In terms of structure, the layout is organized using Bootstrap's grid system, with the card and its contents arranged within a container and rows/columns to ensure proper alignment and responsiveness.

At the end of the HTML body, two script tags are included. The first one imports jQuery from a CDN (Content Delivery Network), specifically version 3.7.0, ensuring that jQuery functionality can be utilized on the webpage. The second script tag links to an external JavaScript file named "index.js", which likely contains code to handle image preview functionality, such as updating the  tag when a user selects an image.

CSS Code

*
{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: sans-serif;
}
.card-header
{
    background: #0f0c29;
    background: -webkit-linear-gradient(to right, #24243e, #302b63, #0f0c29);
    background: linear-gradient(to right, #24243e, #302b63, #0f0c29);
    color: #ffff;
}
#submit-id
{
    background: #0f0c29;
    background: -webkit-linear-gradient(to right, #24243e, #302b63, #0f0c29);
    background: linear-gradient(to right, #24243e, #302b63, #0f0c29);
    color: #ffff;
    padding: 10px 35px;
    font-size: 20px;
    margin-left: 4em;
}
#imageobject
{
    background: linear-gradient(white, white) padding-box,
    linear-gradient(to right, darkblue, darkorchid) border-box;
    border: 4px solid transparent;
}
#heading
{
    font-weight: bold;
    font-size: 20px;
}

The first part, marked with "*", applies to all elements and sets margins, padding, and box-sizing to zero, ensuring consistent layout rendering across different browsers. It also specifies the font-family to be a sans-serif font for better readability.

Next, it targets elements with the class "card-header" to style the header of a card component. It creates a gradient background effect using CSS linear-gradient, transitioning from dark shades of blue and purple to a deeper blue, giving the header a visually appealing look. The text color is set to white for contrast.

The styling for the submit button with the ID "submit-id" follows a similar gradient background pattern as the card header, creating a cohesive design theme across the webpage. It also sets the text color to white, adjusts padding and font size for better button visibility and readability, and adds some margin to position it slightly away from its default location.

For the image with the ID "imageobject", a border is defined using CSS linear-gradient to create a border effect with dark blue and dark orchid colors. This adds a decorative touch to the image preview, enhancing its visual appeal.

Lastly, the styling for the element with the ID "heading" sets the font weight to bold and increases the font size to 20 pixels, making the label "Select Image" more prominent and easier to read.

Method one

$(document).ready(function() {
    console.log('First Method');
    $('#selectimage').on('change', function () {
        console.log('Select Image');
        let image = $(this).prop('files')[0];
        console.log(image);
        $('#imageobject').attr('src', URL.createObjectURL(image));
    });
});

Image-File-Extension-Validation-In-jquery

This JavaScript code is designed to add functionality to a webpage that allows users to select an image file and preview it dynamically. It begins by utilizing jQuery's $(document).ready() function to ensure that the code executes only after the HTML document has been fully loaded. The script logs "First Method" to the console, serving as an indicator that the script is being executed. It then sets up an event listener for the file input field with the ID "selectimage" to listen for changes, such as when a user selects a new file. When a change event occurs, the associated function is triggered. Inside this function, it retrieves the selected image file using jQuery's prop() method, targeting the 'files' property of the input field and selecting the first file from the array. The script then logs information about the selected image to the console for debugging purposes. Finally, it updates the src attribute of the image element with the ID "imageobject" to display the selected image as a preview on the webpage using URL.createObjectURL(), which creates a temporary URL for the selected file. This allows users to preview their selected image before submitting it, enhancing the user experience of the image upload process.

Method two

$(document).ready(function() {
    console.log('Second Method');
    $('#selectimage').on('change',function () {
        let [imagefile] = selectimage.files;
        if(imagefile)
        {
            imageobject.src = URL.createObjectURL(imagefile);
        }
    });
});

Image-File-Extension-Validation-In-jquery

This JavaScript code is designed to execute a specific function when a user selects an image using an HTML input element with the id 'selectimage'. The function is wrapped within the `$(document).ready()` function, ensuring that it executes once the DOM (Document Object Model) is fully loaded.

Inside the function, a console log statement is used to print 'Second Method' to the console, indicating the start of the execution of this function. Following that, an event listener is attached to the 'change' event of the input element with the id 'selectimage' using the jQuery `on()` method.

When the user selects an image using the input element, the event listener triggers a callback function. This callback function retrieves the selected image file using the `files` property of the 'selectimage' element. The `[imagefile] = selectimage.files;` syntax is used to extract the first file from the array of selected files.

Next, a conditional statement checks if an image file is selected. If an image file exists, the code creates a URL for the selected image file using the `URL.createObjectURL()` method. This URL is then assigned as the source (`src`) attribute of an image element referred to as `imageobject`. Presumably, `imageobject` is an HTML image element that will display the selected image on the web page.

Overall, this code snippet demonstrates how JavaScript and jQuery can be used together to dynamically update an image element on a web page based on user input, providing an interactive and responsive user experience.

Method three

$(document).ready(function() {
    console.log('Third Method');
    $('#selectimage').on('change', function (e) {
        imageobject.src = URL.createObjectURL(e.target.files[0]);
    });
});

Image-File-Extension-Validation-In-jquery




This JavaScript code is another implementation for handling the selection of an image file using an HTML input element with the id 'selectimage'. Similar to the previous code snippet, it is wrapped within the $(document).ready() function, ensuring that it executes once the DOM (Document Object Model) is fully loaded.

Within this function, the console log statement logs 'Third Method' to the console, serving as an identifier for this particular function execution.

Following that, an event listener is attached to the 'change' event of the input element with the id 'selectimage' using jQuery's on() method. When a change event occurs (i.e., when the user selects a file using the input element), the callback function defined within the on() method is triggered.

The callback function receives the event object (e), which contains information about the event. Specifically, it retrieves the selected file from the event object using e.target.files[0]. This syntax ensures that the first file selected by the user is obtained.

Once the file is retrieved, the code creates a URL for the selected image file using the URL.createObjectURL() method. This URL is then assigned as the source (src) attribute of an image element referred to as imageobject. Presumably, imageobject is an HTML image element that will display the selected image on the web page.

Method fourth

$(document).ready(function() {
    console.log('Fourth Method');
    $('#selectimage').on('change', function (e) {
        console.log('Select Image');
        let image_reader = new FileReader();
        image_reader.onload = function()
        {
            let image_output = document.getElementById('imageobject');
            image_output.src = image_reader.result;
        }
        image_reader.readAsDataURL(e.target.files[0]);
    });
});

Image-File-Extension-Validation-In-jquery

This JavaScript code represents yet another method for handling the selection of an image file using an HTML input element with the id 'selectimage'. Like the previous examples, it is enclosed within the $(document).ready() function to ensure its execution after the DOM (Document Object Model) has been fully loaded.

Within this function, the console log statement logs 'Fourth Method' to the console, indicating the start of this function execution.

Next, an event listener is attached to the 'change' event of the input element with the id 'selectimage' using jQuery's on() method. When a change event occurs (i.e., when the user selects a file using the input element), the callback function defined within the on() method is triggered.

Inside the callback function, another console log statement logs 'Select Image' to the console, providing a message indicating that the image selection process has started.

The core functionality of this code lies within the FileReader() object. This object is instantiated as image_reader, and an onload event handler is defined for it. When the file reading operation is completed successfully, the onload function is triggered.

Within the onload function, a reference to the HTML image element with the id 'imageobject' is obtained using document.getElementById('imageobject'). This element is assumed to be the target for displaying the selected image.

The src attribute of the image_output element is then assigned the result of the file reading operation, accessed via image_reader.result. This result is the data URL representing the selected image file, obtained by invoking readAsDataURL() on the image_reader object and passing the selected file from e.target.files[0].

Conclusion

I have implemented the four methods in jQuery and all methods work perfectly. You can use any method in your project.

Post a Comment

Previous Post Next Post

Recent in Technology