0

I am facing some issues in the javascript FileReader and its events. I have created an input tag with type file. Here I am picking the image file from the system directory and want to show the picked image preview. If I want to show preview, I need the blob of the file through file reader event. But sometimes event not getting called and not able to show the preview. I mentioned the code below for your reference.

<input type="file" color="light" round #imgUploader (change)="onSelectFile($event)" accept="image/*">

        if (event.target.files && event.target.files[0]) {
            var reader = new FileReader();
            reader.onload = (event: any) => {
              var blobContent = event.target.result;
            }
            reader.onloadstart = (event: any) => {
                console.log("onloadstart", event.target.result)
            }
            reader.onloadend = (event: any) => {
                console.log("onloadend", event.target.result)
            }
            reader.onprogress = (event: any) => {
                console.log("onprogress", event.target.result)
            }
            reader.onabort = (event: any) => {
                console.log("onabort", event.target.result)
            }
            reader.onerror = (event: any) => {
                console.log("onerror", event.target.result)
            }
            reader.readAsDataURL(event.target.files[0]);
            console.log("File reader result : ", reader.result);
          }
    }

Please give a stable solution to show the image preview always.

  • And for "stable solution to show the image preview always", forget about FileReader, you can do all you need synchronously and with less overhead for the browser with a blob URI: `onSelectFile( evt ) { const src = URL.createObjectURL( evt.target.files[0] ); }` – Kaiido Nov 21 '19 at 07:37
  • I am getting like this. **unsafe:blob:http://localhost:8101/ebdcf082-eb54-4ba4-873b-e724f4138f5a** But I need base64 string. If we need to convert from blob to base64, we have to again go with FileReader concept. What to do ? – Sundaramoorthy J Nov 21 '19 at 09:27
  • Whh do you need a base64? 99.9% sure you don't. Fir the unsafe thing, I don't know ionic well but seems you need to wrap the blob URI around _DomSanitizationService.bypassSecurityTrustUrl – Kaiido Nov 21 '19 at 09:35

0 Answers0