Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

html
css
javascript
communitycreator

How to preview images on a webpage using JavaScript

Shubham Singh Kshatriya

From the user experience perspective, it’s convenient to have an image preview as soon as the user selects an image to upload.

In this shot, we will see how we can preview the images on a webpage using JavaScript.

Walk-through

Before writing the code, let’s understand the logic behind it.

We will provide an input box that the user can use to browse the image they want to upload. We will then add an event listener to listen to the change event of the input box. When a file is selected, the change event will be fired and the previewImage() function will be executed.

previewImage()

In order to preview the image, we need to read the contents of the file. JavaScript has introduced FileReader for this exact purpose.

The FileReader() constructor returns an object (we will refer to it as the fileReader) that we can use to read the contents of files selected by the user. We will make use of two events and one method, which is provided by the fileReader, i.e.,

  • onload: this event is triggered each time the reading operation is successfully completed.
  • onerror: this event is triggered each time the reading operation encounters an error.
  • readAsDataURL(): this method reads the contents of the specified file and returns a URL that represents file data.

The uploaded file can be accessed using event.target.files[0]. We will pass this file as an argument to readAsDataURL(), and fileReader will then execute further operations based on the event that occurs.

Code

Note: accept="image/*" will restrict users from selecting files other than images.

RELATED TAGS

html
css
javascript
communitycreator

CONTRIBUTOR

Shubham Singh Kshatriya
RELATED COURSES

View all Courses

Keep Exploring