Search code examples
androidcordovaionic-frameworkcordova-plugins

File Chooser unsupported by cordova


I' m looking for a File chooser plugin for my ionic 5 app, but FileChooser is now unsupported by cordova. Are there other plugins that i can use. Thank you!


Solution

  • Does web API suit your needs instead of Cordova based approach?

    it got decent support nowadays: https://caniuse.com/#search=FileReader

    You could do it this way:

    <ion-header>
      <ion-toolbar>
        <ion-title>
          My super tabs app
        </ion-title>
      </ion-toolbar>
    </ion-header>
    
    <ion-content>
        <ion-card class="welcome-card">
          <img [src]="imageUrl">
        </ion-card>
        <ion-button expand="full">
          <ion-icon slot="start" name="image"></ion-icon>
          <ion-label for="file-input">Choose file to upload</ion-label>
          <input style="position: absolute; opacity: 0; width: 100%; height: 100%" type="file" (change)="loadImageFromDevice($event)" id="file-input" accept="image/png, image/jpeg">
        </ion-button>
    </ion-content>
    

    Your ts:

    import { Component } from '@angular/core';
    import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
    
    @Component({
      selector: 'app-tab1',
      templateUrl: 'tab1.page.html',
      styleUrls: ['tab1.page.scss']
    })
    export class Tab1Page {
    
      imageUrl: SafeResourceUrl;
      dataUrl: string | ArrayBuffer;
    
      constructor(private domSanitizer: DomSanitizer) {}
    
      loadImageFromDevice = (event) => {
        if (!event.target.files[0]) return;
        const file = event.target.files[0];
        if (!file.type.match('image')) return;
        // do blob:
        let blobReader = new FileReader();
        blobReader.readAsArrayBuffer(file);
        blobReader.onload = () => {
          let blob: Blob = new Blob([new Uint8Array((blobReader.result as ArrayBuffer))]);
          this.imageUrl = this.domSanitizer.bypassSecurityTrustResourceUrl(URL.createObjectURL(blob));
        };
        // do base64data:
        /* let dataReader = new FileReader();
        dataReader.readAsDataURL(file);
        dataReader.onload = () => {
          this.dataUrl = dataReader.result;
        };
        dataReader.onerror = (error) => {
          console.log(error)
        }; */
        // handle errors:
        blobReader.onerror = (error) => {
          console.log(error)
        };
      };
    
    }
    

    This will leverage standard web API (input file) and recently all modern browsers / devies support this approach.

    Definitely depends on your use case and for some it won't work.

    Demo: https://stackblitz.com/edit/ionic-4-angular-8-start-template-ywc4r8