37

Browsers don't take full path of local disc, instead they concatenate the filename with fakepath. Is there any way to access the file (image) from fakepath using typescript or angular 2?

I have this:

<img src="{{path}}" />

where my path variable stores the 'fakepath':"C:\fakepath\pic.jpg" in my .ts file.

Edit This question discusses the way to preview image file from fakepath using javascript. If it is possible with Js, then is it not the same in case of ts?

Don Vitali
  • 29
  • 5
Karan Desai
  • 2,422
  • 3
  • 27
  • 56
  • I don't get the problem. How is this Angular or typescript related? – Günter Zöchbauer Aug 22 '16 at 08:41
  • The question you linked has no accepted answer. Also, the other questions talks about *uploading* a file and showing the path from where it was uploaded. DO you also have an uploaded file or do you want to show the file directly form your local disc? – Sebastian Sebald Aug 22 '16 at 08:53

4 Answers4

95

This should do what you want:

<input type='file' (change)="readUrl($event)">
<img [src]="url">
readUrl(event:any) {
  if (event.target.files && event.target.files[0]) {
    var reader = new FileReader();

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

    reader.readAsDataURL(event.target.files[0]);
  }
}
Ruben
  • 7,959
  • 12
  • 58
  • 89
Günter Zöchbauer
  • 490,478
  • 163
  • 1,733
  • 1,404
10

Adding to @GünterZöchbauer answer, this wasn't working for me until I added this:

reader.onload = function(e:any){
   this.url = e.target.result;
}

Prior to adding 'any', I was getting the error:

property 'result' does not exist on type 'eventtarget' 
user875139
  • 1,379
  • 4
  • 20
  • 39
  • 2
    Quite unlikely this code will work. `function(e:any){` should be `(e:any) => {` otherwise `this` won't point to the class containing the code (which is quite likely what you want). – Günter Zöchbauer Jan 27 '17 at 07:38
4

It works when you change the event to type of any. In that way, Angular can access any of its property.

readUrl(event) {
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]);
}

}

Ifesinachi Bryan
  • 1,566
  • 12
  • 18
4

It's working

example.component.html

<input type="file" (change)="onFileChanged($event)" required />
<img [src]="imageShow" height="200"> <br/>

example.component.ts

imageShow: any= '';
onFileChanged(event) {
  this.file = event.target.files[0]
  var reader = new FileReader();
  reader.readAsDataURL(event.target.files[0]);
  reader.onload = (event) => {
   this.imageShow = (<FileReader>event.target).result;
 }

}