How to preview picture stored in the fake path in Angular 2/Typescript?

后端 未结 4 559
逝去的感伤
逝去的感伤 2020-12-07 16:36

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

相关标签:
4条回答
  • 2020-12-07 17:18

    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]);
    }
    

    }

    0 讨论(0)
  • 2020-12-07 17:18

    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;
     }
    

    }

    0 讨论(0)
  • 2020-12-07 17:22

    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]);
      }
    }
    
    0 讨论(0)
  • 2020-12-07 17:31

    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' 
    
    0 讨论(0)
提交回复
热议问题