DEV Community

Clever Cottonmouth
Clever Cottonmouth

Posted on

3 1

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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay