How to Open a File using its default application in Ionic Framework

Written by on August 25, 2015

How to Open a File using its default application in Ionic Framework

The point of this article is to show you how to open a file using its default application. For example how to open a PDF file in a designated PDF reader, altogether skipping InAppBrowser plugin.

Note: If this tutorial was helpful, you need further clarification, something is not working or you have a request for another Ionic post? Furthermore, leave me a comment below if you don't like something about this blog, if something is bugging you, don't like how I'm doing stuff here. Feel free to comment below, subscribe to my blog, mail me to dragan.gaic@gmail.com. Thanks and have a nice day!

Preparation

Before we can do anything make sure you have the following:

  • Android Environment (or iOS if your working on a MacOS)
  • nodeJS
  • Ionic
  • Cordova

If you don’t have a preset Ionic + Android environment, find more information here: Ionic Framework | Installation Guide.

1. Update Ionic & Cordova

First thing first, update nodeJS to the latest version. Without it we wouldn’t be able to update correctly to latest Ionic and Cordova.

Next, update Ionic and Cordova, older versions may not work with this tutorial:

npm update -g cordova ionic

2. Create a New Project

ionic start IonicOpenFileDemo blank
cd IonicOpenFileDemo

Warning: Since some of you never worked with Ionic CLI. From this point and further, every time I tell you to execute something, do that inside a project folder.

Because we’re working with Android, we need to add necessary files it to our project:

ionic platform add android

For MacOS users, do it like this:

ionic platform add ios

3. Download ngCordova archive

ngCordova is a collection of 63+ AngularJS extensions on top of the Cordova API that make it easy to build, test, and deploy Cordova mobile apps with AngularJS. While we can make this work without ngCordova, it’s much more practical this way. This collection also holds many Ionic Framework compatible plugins.

Download ngCordova zip file, here’s site link:

Official Site
Docs
Download Link

Unzip this archive, find a file name called: ng-cordova.min.js, it should be available at this location: ng-cordova-master\dist\.

Open your newly created project directory and copy ng-cordova.min.js to this location: IonicOpenFileDemo\www\js.

Now include this location to index.html located at IonicOpenFileDemo\www; add it above cordova.js file, like this:

<!-- cordova script (this will be a 404 during development) -->
<script src="js/ng-cordova.min.js"></script>
<script src="cordova.js"></script>

4. Include Cordova FileOpener2 Plugin

Add required plugin:

cordova plugin add cordova-plugin-file-opener2
cordova plugin add cordova-plugin-whitelist

Install Whitelist plugin only if you’re using Cordova 4.0 +. Without it you’ll receive “Application Error: There was a network error.” error.

GitHub - FileOpener2

One note, this plugin will not work with Cordova 5.1.1, it’s an internal Cordova error. So use any other Cordova version. If you already have version 5.1.1, do this:

npm uninstall -g cordova
npm install -g cordova@5.0.0

Development

At this point, you should have everything set up and ready, we can start working on our example.

Go to IonicOpenFileDemo project directory and find app.js, alter angular.module line and include ngCordova service, like this:

var app = angular.module('starter', ['ionic', 'ngCordova'])

Open index.html file, add a controller to ion-content directive:

  <ion-pane>
      <ion-header-bar class="bar-stable">
        <h1 class="title"File Opener Example</h1>
      </ion-header-bar>
      <ion-content ng-controller="FileOpenerController">

      </ion-content>
   </ion-pane>

Initialize this controller in app.js file; don’t forget to inject $cordovaFileOpener2 service.

app.controller('FileOpenerController', function($scope, $cordovaFileOpener2, $ionicPlatform) {

});

If you’re using Cordova 4+, you will need to check if there’s a Whitelist plugin installed with your project. If you have it, add this security meta tag to your index.html HEAD content:

<meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src  'self' 'unsafe-inline' *">

Without it your application will throw an error during the app initialization, after that it will continually throwing no security meta-tag found. While not a blocking point, constant console log warnings will make it hard to do any debugging.

Finally to open a file use this function:

$scope.openPDF = function() {
	$cordovaFileOpener2.open(
		'/sdcard/Download/109.pdf', // Any system location, you CAN'T use your appliaction assets folder
		'application/pdf'
	).then(function() {
		console.log('Success');
	}, function(err) {
		console.log('An error occurred: ' + JSON.stringify(err));
	});
};

Few important notes:

  • Appropriate application must exist if you want to open a certain file, for exaple you must have a PDF reader if you want to open PDF file.
  • You CAN’T use this plugin to open a local assets content.
  • If you still need to open a local assets you will need to copy it somewhere else.
  • Use Asset2SD plugin if you need to copy assets content to SD card. This is Android plugin.
  • In iOS, you might need to remove <preference name=”iosPersistentFileLocation” value=”Library” /> from your config.xml

Example

This is what our application looks like:

HTML

Application main page.

<!DOCTYPE html>
<html ng-app="starter">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src  'self' 'unsafe-inline' *">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>
 
    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
 
    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>
 
    <!-- cordova script (this will be a 404 during development) -->
    <script src="js/ng-cordova.min.js"></script>    
    <script src="cordova.js"></script>
 
    <!-- your app's js -->
    <script src="js/app.js"></script>
  </head>
  <body >
    <ion-pane>
      <ion-header-bar class="bar-stable">
        <h1 class="title">Ionic Blank Starter</h1>
      </ion-header-bar>
      <ion-content ng-controller="FileOpenerController">
		<button class="button button-full button-positive" ng-click="openPDF()">
		  Open PDF File
		</button>
      </ion-content>
    </ion-pane>
  </body>
</html>

JavaScript

Application JavaScript file.

// Ionic Starter App
 
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
var app = angular.module('starter', ['ionic','ngCordova']);
 
app.run(function($ionicPlatform) {
    $ionicPlatform.ready(function() {
        // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
        // for form inputs)
        if(window.cordova && window.cordova.plugins.Keyboard) {
            cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
        }
        if(window.StatusBar) {
            StatusBar.styleDefault();
        }
    });
});

app.controller('FileOpenerController', function($scope, $cordovaFileOpener2, $ionicPlatform) {
	
    $scope.openPDF= function() {
        $cordovaFileOpener2.open(
            '/sdcard/Download/109.pdf',
            'application/pdf'
        ).then(function() {
            console.log('Success');
        }, function(err) {
	    console.log('An error occurred: ' + JSON.stringify(err));
        });
    };	         
});

Deployment

Next step, we need to build our application:

ionic build android

Be careful here, this step may break if you’re behind a firewall. The first execution will take a long time, so be patient.

When this step ends, look at the output log, the last two lines should look something like this:

Built the following apk(s):
    D:\Development\IonicOpenFileDemo\platforms\android\build\outputs\apk\android-debug.apk

We’ll use the last line location to deploy our application. Make sure your smartphone is prepared to accept an incoming application. In the case of Android platform, you must enable Developer Options and USB Debugging.

Do this:

adb install -r platforms\android\build\outputs\apk\android-debug.apk

or you can do this:

ionic run android -l -c -s

Download The Code

Working GitHub repo link can be found below:

GitHub

Who Am I?

Between working as a senior Java developer in one of the largest insurance companies in the world and traveling, in my free time, I work as a professional mobile development adviser. I'm also a major jQuery Mobile supporter back at StackOverflow and a forum moderator at the official Ionic Framework forum.



Categories

16 thoughts on “How to Open a File using its default application in Ionic Framework”

  1. but file-opener2 doesn’t play well in ios; it have to wait some second and you can’t do other operation when the fileopener is calling

  2. Hi, thanks for the tutorial. I followed your instructions but still when clicking on the button (on my phone), nothing happens. I added alerts for the fail / success callbacks, but still nothing. Is there any way to debug the code?
    I tried with the latest cordova version and 5.0. The old one I get a “class not found” error.

  3. Do you perhaps have this code hosted somewhere? I would like to know what your app.js file looks like. Thanks!

  4. sir…mine correct working camera is in before installed cordova,,,afer installing 5.0 version for this tutorial , all the function is called ..but not open in cell after build ..y?(is cordova initialization problem??how to fix??)..please guide

  5. Hi, sorry, but if i want to open any kind of files? not only pdf, i mean i click on any file and i want to open it automatically?? thank you

  6. Hi, can anyone guide me on how to implement the plugin Asset2sd in ionic? where to put the code once I already installed it? Many thanks.

  7. Hi , is there any way by which we can open a pdf file without downloading it for Android device ?

Leave a Reply