Sooner or later you will need to upload a file from your hybrid mobile application to some remoter server location. This is not a problem if this piece of information is a string, but what if we have a large binary file? We can convert it to BASE64 format string representation, but this process is resource and memory heavy, especially if we’re talking about large files.
 
There’s a better solution for this problem, we can use Cordova File Transfer plugin which is part of a ngCordova collection.
 
This plugin is excellent if you need to:
 
  • Upload one or several files of any size
  • Download future application updates without major release
  • Download various remote resources
This article will show you how to do this on a real life example. I will embed all the code you need to successfully implement this feature and if you need a working starter application you can find it on the next page.
 
 

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

PS. If you want my help, if possible (even if it takes you some time to do that), create a working example I can play with. Use Plunker for AngularJS based questions or jsFiddle for jQuery/jQuery Mobile based questions.


 

Table of Contents

 
Click here if you want to see other tutorials, or articles about the Ionic framework (themes, templates, plugins, tutorials)
 

Preparation

 
First make sure everything is in order and you have all that is required to reuse this example.
 
Make sure you have these:
 
  • Android Environment (or iOS if your working on a MacOS)
  • nodeJS
  • Ionic
  • Cordova
If you never created an Ionic Framework application you can find more information here: Ionic Framework | Installation Guide.
 

1. Update Ionic & Cordova

 
First check if you have a latest nodeJs version, you will not be able to properly update Cordova and Ionic through CLI without it.
 
Update Ionic and Cordova, older versions may not work with this tutorial:
 
npm update -g cordova ionic
 

2. Create a New Project

 
ionic start IonicFileTransferDemo blank
cd IonicFileTransferDemo
 
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.
 
We’re going to add Android platform to our project:
 
ionic platform add android
 
MacOS users can also add iOS platform:
 
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: IonicFileTransferDemo\www\js.
 
Now include this location to index.html located at IonicFileTransferDemo\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. Install Cordova File Transer and Whitelist Plugin

 
Next line will import and install necessary plugins into newly created project:
 
cordova plugin add org.apache.cordova.file-transfer
cordova plugin add cordova-plugin-file
cordova plugin add cordova-plugin-whitelist
 
If you’re using Cordova 5.0.0 you will already have preinstalled Whitelist plugin.
 
We also need Cordova File plugin so we can access device file system.
 
GitHub - File Transfer GitHub - File GitHub - Whitelist
 
 

Development

 
At this point, you should have everything set up and ready, we can start working on our example.
 
Go to IonicFileTransferDemo 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 Transfer Example</h1>
      </ion-header-bar>
      <ion-content ng-controller="FileTransferController">
      </ion-content>
    </ion-pane>
 
Initialize this controller in app.js file; don’t forget to inject $cordovaFileTransfer service, like this:
 
app.controller('FileTransferController', function($scope, $cordovaFileTransfer, $timer) {

});
 
Now we need to initialize Whitelist plugin; add this meta tag to 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' *">
 
We’ll use two distinct functions; one will download a test file while the other one will upload it back to test remote web server:
 
  $scope.testFileDownload = function () {
    // Function code goes here
  }
  $scope.testFileUpload = function () {
    // Function code goes here
  }
 
Next function can be used to download a file from a remote location:
 
      // File for download
      var url = "http://www.gajotres.net/wp-content/uploads/2015/04/logo_radni.png";
	  
      // File name only
      var filename = url.split("/").pop();
	  
      // Save location
      var targetPath = cordova.file.externalRootDirectory + filename;

      $cordovaFileTransfer.download(url, targetPath, {}, true).then(function (result) {
          console.log('Success');
      }, function (error) {
          console.log('Error');
      }, function (progress) {
          // PROGRESS HANDLING GOES HERE
      });
 
While this next function will upload it to a device/remote location:
 
     // Destination URL 
     var url = "http://example.gajotres.net/upload/upload.php";
	 
     //File for Upload
     var targetPath = cordova.file.externalRootDirectory + "logo_radni.png";
	 
     // File name only
     var filename = targetPath.split("/").pop();
	 
     var options = {
          fileKey: "file",
          fileName: filename,
          chunkedMode: false,
          mimeType: "image/jpg",
	  params : {'directory':'upload', 'fileName':filename} // directory represents remote directory,  fileName represents final remote file name
      };
	  	  
      $cordovaFileTransfer.upload(url, targetPath, options).then(function (result) {
          console.log("SUCCESS: " + JSON.stringify(result.response));
      }, function (err) {
		  console.log("ERROR: " + JSON.stringify(err));
      }, function (progress) {
          // PROGRESS HANDLING GOES HERE
      });
 
Continue Reading

  • Toby Okeke

    Thanks alot for this tutorial. It has helped me a very very serious way. Im really grateful. Have a good day.

    • Thank you very much 🙂

      • anjali jibhakate

        hi there, Your tutorial is very good, but could you guide me in how to download the table data into xls format in external storage?

  • Rudi

    Hai Gajotres, thank you for your tutorial. I am a newbie of ionic and angular. And i follow this tutorial but after i install in android 4.1.2 i getting error like this. Can you help me with this issue? fyi. i can access google and other online stuff, i am checking my internet connection doesn’t have a problem. Thanks

    • Rudi

      But if i am running in web hosting they run like the image below. But if i wont clik all button they doesn’t change anythings.

      • Have you installed Whitelist plugin? If you did, remove it and add it back.

        • Rudi

          Yes, I am already install, remove, and install again. BUt still same error found, i also got info when i run in android they said i have multiple ip address: 1. ethrnet ip 2. wifi and 3. virtualbox ip .. so i chose 2 (my wifi internet connection) but still error i found

  • Kent Kawahara

    Hello Gajotres

    First, thank you so much for this tutorial! It help me successfully download a picture from my server and I couldn’t have done it without your tutorial.

    But I’ve been stuck. I set my download path to be cordova.file.dataDirectory + “directoryName” + “imageName.png”. I set the path as a scope variable, $scope.imagePath = cordova.file.dataDirectory + “directoryName” + “imageName.png” and try to display it on my view as
    ng-src = {{imagePath}}, but nothing appears. Any idea what I could be doing wrong?

    Thanks in advance!

    • Hi Kent, instead of using primitive variables like imagePath try using dot notation like this:

      $scope.image = {
      imagePath : ”
      }
      $scope.image.imagePath = cordova.file.dataDirectory + “directoryName” + “imageName.png”;

      Ionic heavily relies on child scopes, and why you may not see this, only way for them to communicate is if you use dot notation. Try searching through my blog, you’ll find an article on this topic.

      Another thing, have you check id that png file really do exist at that location?

      • Kent Kawahara

        Hello Gajotres

        Thanks for the quick response!

        I tried using the dot notation, as you described and I still get the same result. I also checked to see if the directory and file exists, using cordovaFile.checkFile and cordovaFile.checkDir and I have gotten success call backs.

        I have read from another article that you must create a blank directory and file before downloading into it. I’ll try it out and update you on the results

        • santiago

          I have the same problem, decompress a Zip in “data / data / com.myApp / ImagesZip” and does not read the images. 🙁
          You found a solution?

          • Kent Kawahara

            See my response above

        • Tell me are you testing this on iOS or Android. And if you’re using Android, what device?

          • Kent Kawahara

            Hello Gajotres

            I found out what the problem was. So, it was downloading perfectly fine. There was nothing wrong with the code.

            The problem was with the emulator. I was testing my app with Genymotion, using a Samsung S5 emulator. Using livereload does not show all features and functions that a real phone should. So, when I tested it out on my real device, the picture showed up fine! Whenever I’m testing native features, I will be using the command, “ionic run android -c -s”.

  • R.O.

    Hello sir,
    Many thanks for all your tutorials that have greatly helped and helping us in so many ways.
    Please, i have problem at hands to solve though i’m a newbie in angular/ionic.

    1) I have a form that contains several inputs to collect personal info like names, gender, DOB, Occupation etc. At the bottom of the form i have image tag and a button to display and capture image respectively. I was able to capture and displayed the captured image.

    PROBLEM STATEMENT:
    1) I would like to save all the personal info including the captured image on a local storage. Why? because of bad network.

    2) I would like to retrieve the saved info and image and upload to a remote server.

    Please, i would be so grateful if you can illustrate this with a simple and short tutorial as you wish.
    Thanks once again.

    • This should not be a problem. Create a json object holding data you would like to transfer at some point in time. Convert image to BASE64 string representation before you include it into json. Stringify that json and save it to local storage.

  • Danny

    Hi, thanks for the tutorial. I understand that you can upload from a specific location but how do I upload a file from a File Input location?

  • Jan Klug

    Hi there, fantastically clear tutorial! What kind of server do I need to be able to accept a bunch of .wav files from a cordova app and then batch process them into a MySQL database along with their corresponding metadata?

    • It depends on process itself. Simple BLOB storing is not resource heavy but format conversion on the other hand is. What are you trying to do?

  • TemmyThorpe ‘sureboi’ Fatayo

    Hello Gajotres.. Thanks for this wonderful tutorial.I hosted the upload.php on IIS and everything i tried to upload it comes back with Upload error!….I dont know what the issue might be..i did everything i specified in the tutorial…Pls assist

    • Vegard Aaberge

      If you get error Null, then try to make sure that Destination URL is correct, and you have uploaded the php file to your own server.

  • Vegard Aaberge

    Thank you so much for this amazing tutorial, really helped me move forward.

  • Leo

    Is There Any way to display the progress of the download in the status bar How Common download huh?

    • You can use onprogress property:

      fileTransfer.onprogress = function(progressEvent) {
      // Line below should give you a percentage
      //progressEvent.loaded / progressEvent.total
      }

      Use this percentage with Ionic progress bar component.

      • Greg Sithole

        Hi what is the Ionic Progress Bar Component….. I already have the on progress stuff but I’m not sure on the progress bar

  • amro khaled

    how to console.log() in mobile app ?! cordova is not defined while serve in chrome.. ?!

    • console.log() should work in your mobile app. Just use Chrome or Safari remote debugging.

  • Encrypted in what way?

  • Jared

    Hello and thanks for the great tutorial!! Can I ask you if you can point me in the right direction regarding the upload server. I need a cloud based solution for my Ionic App. I have been through AWS S3, Microsoft Azure Blob Storage, written API’s in C# and Node for each and I am still struggling to get anything to work. I have been at this for days now. It is killing me! lol. I appreciate any help!

    • Unfortunately, I never used Ionic with AWS S3 or Microsoft Azure. I’m currently working on a project which requires Microsoft Azure Blob Storage but I talked with several developer who had a great experience with AWS S3.

      Can you describe me your problem?

      • Jared

        Hello, thanks for getting back so quickly! I am building a prototype so I am short on time. So I ditched S3 and Azure due to the complications needed for my app. I did just find a company that will let you you upload you images and then they can perform transformations on the fly.Its called Cloudinary, it will do in a pinch. I appreciate your help! I read allot of your stuff on the Ionic forums. Cheers!

        • Thanks for this info, I’ll check it myself.

    • Raj Jirapure

      Hello Jared.. I am having a query, Is it possible to download a .bin file from AWS S3 storage using ionic framework similarly as you shown in this tutorial. Or there are some different methods that I have to work on?. I am struggling to get file from AWS S3. Please help me out from this and thank you.

  • 1. You can use formula I gave you to calculate current transfer percentage
    2. Use default HTML5 progress bar element

    3. Use AngularJS two way binding for animation. Let’s say variable currentPercentage holds current percentage.

    Use it like this:

    4. Style this progress bar with CSS

  • Indika Ratnayake

    Thank you very much for the tutorial. How do I modify this to download a file only if the file is new. (For example if the modified date of the file on the server is newer than the file on the device) ?

    • Please give me some time to think about it.

      • Indika Ratnayake

        Thank you.

  • ZiLang

    I got the following error message when I tried your testFileUpload

    > ERROR: {“code”:1,”source”:”nulllogo_radni.png”,”target”:”http://localhost:8000/upload.php”,”http_status”:null,”body”:null,”exception”:null}

    The server php is running by:

    > php -S upload.php

    How to debug it? Thanks

  • how to choose any file from directory…and how to to upload to server

  • uma

    I have DataUri image on dom how can i upload it to the serve ? should i convert it to blob before sending it to server ?
    which way is better ?

  • KB

    Is there a way I can have a look at remote FTP server directory before download?

  • a_user

    hi, im getting the error ‘Error: cordova is not defined $scope.testFileDownload@http://localhost:8100/js/controllers.js:1749:11…’, does anyone know how to fix this?

  • Alugbin Abiodun

    Nice tutorial!! But please can we use this plugin for ionic v2???
    Thanks

  • Goutam Singha

    In iPhone, I can’t see the downloaded files. How to see them in iPhone. Is there any file manager available for it?

  • truyentranhhot viet nam

    It’s great article. Thanks a lot. I got this error ‘Not allowed to load local resource: file:///storage/emulated/0/-MTO-%252520-%252520SINS%252520–Credit.jpg’ when trying to display the image which i downloaded to external storage. any ideas ?

  • Pedro Sanchez

    i have the same problem, how can fix it?? thanks

  • Arthur

    It doesn’t work. I don’t know why.

    • Fabien

      It works. I don’t know why.

  • Mohan Gopi

    I am trying to upload taken image to my FTP but i have password and username for that and also what should i give to fileKey field in this blog fileKey = “file” is given what that means can some one help and in my project i always invoke only the error part

  • tayyaba farooqui

    how can i use node js instead of php for server side??

  • Tony

    Hi Dragan, this is great and I’m using your example for upload. Could you please point me how to upload multiple images/files at once? Thank you!

    • GulamAbbas

      I am doing same thing I will post here my solution when done.

  • Raj Jirapure

    Hi Dragan, thank you for simple and best tutorial for the download and upload functionality using cordova file transfer plugin. It works fine. I am having a query, Is it possible to download a .bin file from AWS S3 storage using ionic framework similarly as you shown in this tutorial. Or there are some different methods that I have to work on?. I am struggling to get file from AWS S3. I appreciate any help from your side!

  • Gustavo Higuchi

    try this cordova plugin add cordova-plugin-file-transfer

  • technotip

    Can you please post server side code for this?
    PReferably Node.js

    • You can find it on the second page, a PHP example.

      • amolbapat

        great tutorial…. One query though…, At what location do i create this PHP file??

  • Matte

    Hello can you help me, please?
    When I try to upload a file (database file) to a ftp server with basic auth (ftp://user:password@url/path), the app crash and, in the system log write this:
    *** Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘*** setObjectForKey: object cannot be nil (key: headers)’ ***

    Can you help me with this?

    Thanks!

  • DC

    Dragan, I’m new at this and have several questions. For the file upload url was the endpoint a manual entry in the hosts file/what ip is needed or was http create server used ? Is the upload.php file placed in the upload directory ? Thanks

  • Dhameer Govind

    Thanks for this, I seem to be getting an error”move_uploaded_file(): The second argument to copy() function cannot be a directory in”. Is this something to do with server pemissions?

  • Jose Enrique Estremadoyro Fort

    How does upload.php looks?

  • Dhameer Govind

    Hi there. I am getting the following error “ERROR: {“code”:1,”source”:”/storage/emulated/0/Pictures/logo_radni.png”,”target”:”myURL/upload/upload.php”,”http_status”:200,”body”:null,”exception”:”/storage/emulated/0/Pictures/logo_radni.png: open failed: EACCES (Permission denied)”}”

    • Dhameer Govind

      I’m testing on android marshmallow 6.0 and 6.0.1

    • Dhameer Govind

      okay. the problem was that for some reason my app did not have the storage permission on, under the android app management settings.

  • Warisha

    Hi,
    i tried it it downloaded successfully but It is not working for video .Can you please help me how to download video ?
    this code is just for download images.
    Thanks in advance

  • function($scope, $cordovaFileTransfer, $timer) {…
    Why do we need $timer ?

  • Azhar

    Why I am getting exception Eaccess permission denied.
    As i added
    in manifest.xml file but still getting same problem

    • Azhar

      I am talking about filetranfer.upload method