Image preview before upload in angular 5

后端 未结 7 1688
逝去的感伤
逝去的感伤 2020-12-15 10:17

.html

  
  \"your
7条回答
  •  [愿得一人]
    2020-12-15 10:33

    I know I'm late but just ran into this problem for both image and audio. The above solutions worked just fine for images but not so well for audio. I eventually got it all working by using a URL object instead of FileReader object that everyone is using. something like the following

    component.ts file ~

    imgSrc = 'assets/path/to/default/image.jpeg'
    
    imgFileSelected(event: any) {
      if (event.target.files && event.target.files[0]) {
        this.imgSrc = URL.createObjectURL(event.target.files[0]);
      }
    }
    

    My component.html looks like~

     
    

    Finally I created a custom pipe to rid the console of warnings. my pipe is as follows~

    @Pipe({
      name: 'sanitizerUrl'
    })
    export class SanitizerUrlPipe implements PipeTransform {
    
      constructor (
        private sanitize: DomSanitizer
      ) {}
    
      transform(value: string): SafeUrl {
        return this.sanitize.bypassSecurityTrustUrl(value);
      }
    }
    

    To see how I used this for the audio tag you can check out this link. It's only 2 extra lines of self-explanatory code.

提交回复
热议问题