How to Preview an Image Using JavaScript Before Upload

Robin
Updated on November 11, 2022

We often upload images to a website. It's a great experience when we can preview the image before pressing the upload button. This is what you are going to learn in this article.

After getting the image file in JavaScript, use FileReader() constructor to convert the file into a data URL. Then set this value in the src attribute of a <img> tag. The browser will display the image using that data URL string.

Let's see how we can display an image on the web page using JavaScript before uploading it to the server.

Preview an Image Before Uploading Using JavaScript

Whenever a user chooses an image file with the <input> field, we will extract that image in our JavaScript file and then add it to the DOM.

These are the 3 simple steps to preview an image using JavaScript:

  1. Create a web page layout to select and display an image.
  2. Covert the image into a data URL using JavaScript.
  3. Show the selected image on the page with a <img> tag.

Let's discuss each step in detail with an example and code samples.

Also Read: File Extension/Type Validation in JavaScript Before Upload

Step 1: Create a Web Page Layout With HTML and CSS

I am creating an HTML structure for my example. Here I have 2 main sections. One part will display the selected image and another part has the <input> field to choose the file.

You can use a <input> field in different ways. Define the type of your input field using the type attribute. For choosing files set type="file" in the <input> tag.

          <div class="container">
    <div class="preview_image">
        <!-- Default text if no image is selected -->
        <p id="default-text">Image Preview</p>

        <!-- Selected image will display here -->
        <img src="" class="image" id="image-preview">
    </div>

    <!-- Input field to choose an image file -->
    <input type="file" id="select-image">
    <label for="select-image">
        <?xml version="1.0" ?><svg viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg">
            <path
                d="M1344 1472q0-26-19-45t-45-19-45 19-19 45 19 45 45 19 45-19 19-45zm256 0q0-26-19-45t-45-19-45 19-19 45 19 45 45 19 45-19 19-45zm128-224v320q0 40-28 68t-68 28h-1472q-40 0-68-28t-28-68v-320q0-40 28-68t68-28h427q21 56 70.5 92t110.5 36h256q61 0 110.5-36t70.5-92h427q40 0 68 28t28 68zm-325-648q-17 40-59 40h-256v448q0 26-19 45t-45 19h-256q-26 0-45-19t-19-45v-448h-256q-42 0-59-40-17-39 14-69l448-448q18-19 45-19t45 19l448 448q31 30 14 69z" />
        </svg>
        Choose an Image
    </label>
</div>
        

To make the web page looks good, I will add the following CSS style. It will add style to those HTML elements.

          body {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    background-color: #fdfdfd;
    font-family: 'Open Sans', sans-serif;
}

.container {
    width: 500px;
    padding: 35px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    border-radius: 15px;
    background: #ffffff;
    box-shadow: rgba(99, 99, 99, 0.2) 0px 2px 8px 0px;
    -webkit-border-radius: 15px;
    -moz-border-radius: 15px;
    -ms-border-radius: 15px;
    -o-border-radius: 15px;
}

.preview_image {
    width: 100%;
    height: 200px;
    border-radius: 10px;
    margin-bottom: 40px;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 2px dashed #6b6969;
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    -ms-border-radius: 10px;
    -o-border-radius: 10px;
}

#default-text {
    font-size: 20px;
    color: #918f8f;
}

.image {
    max-width: 100%;
    max-height: 100%;
    display: none;
}

#select-image {
    display: none;
}

label {
    display: flex;
    align-items: center;
    background: #025bee;
    padding: 18px 30px;
    color: #ffffff;
    border-radius: 5px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    -ms-border-radius: 5px;
    -o-border-radius: 5px;
}

label svg {
    fill: #ffffff;
    width: 20px;
    height: 20px;
    margin-right: 8px;
}
        

Now open the HTML file in a browser to see how it looks. By clicking the button, you can select any image file from your computer.

Create a Web Page Layout With HTML and CSS to preview image before upload

Step 2: Convert the Image File Into a Data URL Using JavaScript

Now we can extract the selected image file using the JavaScript change event on the input field. When the file changes, the callback function will run.

You can get the image file from the target property. Now convert the image file into a data URL using the FileReader() constructor function.

          const fileInput = document.getElementById('select-image');
const imagePreview = document.getElementById('image-preview');
const defaultText = document.getElementById('default-text');

// Lister to the change event on the <input> element
fileInput.addEventListener('change', (event) => {
    // Get the selected image file
    const imageFile = event.target.files[0];

    if (imageFile) {
        const reader = new FileReader();

        // Convert the image file to a string
        reader.readAsDataURL(imageFile);

        defaultText.style.display = 'none';
        imagePreview.style.display = 'block';

        // FileReader will emit the load event when the data URL is ready
        // Access the string using result property inside the callback function
        reader.addEventListener('load', () => {
            // Set the value for the <img> src attribute
        });
    } else {
        // Set the default values
        imagePreview.style.display = 'none';
        defaultText.style.display = 'block';
    }
});
        

Call the readAsDataURL() method with the image file. When the data URL string is ready, it will trigger the load event.

Inside the callback function of this load event, you can access the data string from reader.result property and use it for the src attribute of a <img> tag.

You can also save the image to localStorage by storing that data string for future use. Whenever you need just get the string from the storage and show it on the page.

Step 3: Display Uploaded Image File With JavaScript

After converting the image file into a data URL, it's time to show that on the web page. I am calling the setAttribute() method to set the src attribute.

The value of this attribute will be the data URL string which is available in the result property inside this callback function.

          const fileInput = document.getElementById('select-image');
const imagePreview = document.getElementById('image-preview');
const defaultText = document.getElementById('default-text');

// Lister to the change event on the <input> element
fileInput.addEventListener('change', (event) => {
    // Get the selected image file
    const imageFile = event.target.files[0];

    if (imageFile) {
        const reader = new FileReader();

        // Convert the image file to a string
        reader.readAsDataURL(imageFile);

        defaultText.style.display = 'none';
        imagePreview.style.display = 'block';

        // FileReader will emit the load event when the data URL is ready
        // Access the string using result property inside the callback function
        reader.addEventListener('load', () => {
            // Set the value for the <img> src attribute
            imagePreview.setAttribute('src', reader.result);
        });
    } else {
        imagePreview.setAttribute('src', '');
        imagePreview.style.display = 'none';
        defaultText.style.display = 'block';
    }
});
        

If there is no image file, the else block will run. Here, I am setting the default value for the src attribute and show the default text on the page.

After completing this setup, we can check our web page how it looks after selecting an image.

Preview an Image Before Uploading Using JavaScript

It's working properly. Whenever I choose an image, it displays the selected image on the page. Now you can add another button to upload it to a server.

You can also use the same method to preview multiple images with JavaScript just by changing a few things. All the steps are almost the same.

Conclusion

This feature really provides a great user experience. Because anyone can see which image they are uploading to the website. If they choose the wrong image, they can change it right away.

I hope today's topic was clear to you. It is very easy to preview an image on the web page using JavaScript before uploading.

Related Posts