14
Dec

Ionic – Opening a downloaded file with ngCordova’s $cordovaFile.

After downloading our files to our directory, logically, the next step was to display those files in the app.

The documentation on the ngCordova site for listing the contents of a directory, is beyond scant, as there is no mention of any function that would allow you to do it.

After going into the source code, we found a function that would nicely do the trick…

$cordovaFile.listDir(filePath, true).then(function(result) {
      // Success!
}, function(err) {
      // An error occurred. Show a message to the user
});

Listing the downloaded file…

After checking that the device is ready, with the $ionicPlatform.ready(function() {}) function. We can then list the file(s) that are in the directory that we specify.

To stop us getting an error on the page when we don’t have any downloads (or a directory has been created), we initially create a directory by calling the $cordovaFile.createDir() function, and then call the $cordovaFile.listDir() function afterwards.

If we haven’t downloaded any files yet, the result will be an empty array, but we won’t incur an error (because we’ve created a directory if there wasn’t one). If we have downloaded a file(s) then the $cordovaFile.listDir() function will return them.

Here is our controller code:

  
var directory = 'downloads';
function allDownloads() {
  return $ionicPlatform.ready(function() {})
  .then(function() {
    return $cordovaFile.createDir(directory, false);
  })
  .then(function(result) {
    return $cordovaFile.listDir(directory, {});
  });
};

As with all plugins, we had to inject $cordovaFile as a dependency into our service.