DEV Community

Clever Cottonmouth
Clever Cottonmouth

Posted on

Show image after upload without any plugins

fileBrowseHandler(files: any) {
    if (files.target.files && files.target.files[0]) {
      const reader: FileReader = new FileReader();
      reader.readAsDataURL(files.target.files[0]);
      reader.onload = () => {
        this.preview = reader.result;
      };
      reader.onerror = (error) => {
        console.log('Error: ', error);
      };
    }
  }
Enter fullscreen mode Exit fullscreen mode

Here is the explanation for the code above:

  1. files.target.files is an array-like object. It contains the files that the user has selected.
  2. FileReader object lets web applications asynchronously read the contents of files.
  3. reader.readAsDataURL(files.target.files[0]) is used to read the contents of the specified Blob or File.
  4. reader.onload is an event handler which is called when the read operation successfully completes.
  5. reader.onerror is an event handler which is called when the read operation fails.
  6. this.preview is a variable which stores the base64 image data of the selected file.

Top comments (0)