Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I display an image using Typescript and Angular 4

I am very new to typescript and web development in general so I am sorry if my code is terrible. Anyways, I am having an issue displaying a "preview image" for a profile picture upload. I am using ng2-file-upload to upload my image to the server and that part is working correctly. Before I click the upload button I want to display the selected image on the page right after it has been selected. Currently I am trying to display the image by retrieving the src property from the HTMLImageElement but the src property appears to be empty.

import { Component, OnInit } from '@angular/core';
import {  FileUploader } from 'ng2-file-upload/ng2-file-upload';

const URL = 'http://localhost:4200/api/upload';

@Component({
  selector: 'app-view-profile',
  templateUrl: './view-profile.component.html',
  styleUrls: ['./view-profile.component.css']
})
export class ViewProfileComponent implements OnInit {

  constructor() { }
  public uploader: FileUploader = new FileUploader({url: URL, itemAlias: 'newProfilePicture'});
  title: string;
  previewImage: any;
  tempImage: any;
  source: string;

  imagePreview(input) 
  {
      document.getElementById("previewImage").style.display="block";
      
        console.log("Image is selected")
        this.previewImage = document.getElementById("previewImage");
        console.log(this.previewImage);
        
        this.source = (<HTMLImageElement>document.getElementById('previewImage')).src
        console.log("Image Source: " + this.source + " Should be inbetween here");
        
      
      //var reader = new FileReader();
        
        //console.log(this.previewImage);
      
  }

  ngOnInit() {
  	this.title = 'View or Update Your Profile';
  	this.uploader.onAfterAddingFile = (file)=> {file.withCredentials = false;};
  	this.uploader.onCompleteItem = (item:any, response:any, status:any, headers:any) => {
        console.log("ImageUpload:uploaded:", item, status, response);
    //this.imagePreview();


    };
  }


}

And here is my HTML

<div class="container">
    <h1>{{title}}</h1>

    <div>

        <input type="file" id="previewImage" (change)="imagePreview(this);" name="newProfilePicture" ng2FileSelect [uploader] ="uploader" />
        <button type="button" class="btn btn-success btn-s" (click)="uploader.uploadAll()" [disabled]="!uploader.getNotUploadedItems().length">
          Upload Your File
        </button>
    </div>
</div>
like image 255
Kenny Ho Avatar asked Nov 02 '17 03:11

Kenny Ho


2 Answers

You achive this by this simple function :

Template :

<img [src]="url" height="200"> <br/>
<input type='file' (change)="onSelectFile($event)">

Component :

onSelectFile(event) { // called each time file input changes
    if (event.target.files && event.target.files[0]) {
      var reader = new FileReader();

      reader.readAsDataURL(event.target.files[0]); // read file as data url

      reader.onload = (event) => { // called once readAsDataURL is completed
        this.url = event.target.result;
      }
    }
}

Here is the working example of it, please check this out:

WORKING DEMO

like image 70
Vivek Doshi Avatar answered Sep 18 '22 12:09

Vivek Doshi


Template :

<input type='file' (change)="readUrl($event)">
<img [src]="url">

Component :

 readUrl(event:any) {
      if (event.target.files && event.target.files[0]) {
          var reader = new FileReader();

          reader.onload = (event:any) => {
              this.url = event.target.result;
          }

          reader.readAsDataURL(event.target.files[0]);
      }
 }

T tried it, and it works without any error.

like image 31
Iron shield Avatar answered Sep 17 '22 12:09

Iron shield