Recommended Android/IOS file chooser plugin

Well I’ve done it like this, this should work on Android and on iOS but I’ve only tested it on Android:

      function checkFileType(path, fileExt) {
        return path.match(new RegExp(fileExt + '$', 'i'));
      }

      function chooseFileOk(deferred, uri, fileExt) {
        $log.debug('FileManager#chooseFile - uri: ' + uri + ', fileType: ' + fileExt);

        if (!checkFileType(uri, fileExt)) {
          deferred.reject('wrong_file_type');
        } else {
          deferred.resolve(uri);
        }
      }

      function chooseFileError(deferred, source) {
        $log.debug('FileManager#chooseFile - ' + source + ' error: ' + JSON.stringify(error));

        // assume operation cancelled
        deferred.reject('cancelled');
      }

      var chooseFile = function (fileExt) {
        var deferred = $q.defer();

        // iOS (NOTE - only iOS 8 and higher): https://github.com/jcesarmobile/FilePicker-Phonegap-iOS-Plugin
        if (ionic.Platform.isIOS()) {

          FilePicker.pickFile(
            function (uri) {
              chooseFileOk(deferred, uri, fileExt);
            },
            function (error) {
              chooseFileError(deferred, 'FilePicker');
            }
          );

        // Android: https://github.com/don/cordova-filechooser
        } else {

          fileChooser.open(
            function (uri) {
              chooseFileOk(deferred, uri, fileExt);
            },
            function (error) {
              chooseFileError(deferred, 'fileChooser');
            }
          );
        }

The main function is called “chooseFile” and I can pass it a “fileExt” parameter to restrict the kind of files that can be selected (e.g. only ‘pdf’ files).

Typically you’d package the function inside a service. It returns a promise so you then use it like:

   FilePickerService.chooseFile('.pdf').then(function(url) {
       // do something with the selected file
   }).catch(error) {
       // something wrong, log it or show a message
   });

The code uses 2 plugins: FilePicker for iOS and fileChooser for Android. Install them as follows:

ionic plugin add https://github.com/jcesarmobile/FilePicker-Phonegap-iOS-Plugin.git
ionic plugin add https://github.com/don/cordova-filechooser

Does that make sense?

2 Likes