Skip to main content

File Upload & Download With ng-cordova File Transfer Plugin In Ionic Framework


Using the AngularJS extension set, ngCordova, with Ionic Framework and the Apache Cordova File Transfer plugin, you can easily upload files to a remote server and download files from a remote server.


1.Create the project


ionic start Test blank
cd Test
ionic platform add android


2.Add Plugin
  1. org.apache.cordova.file-transfer
This plugin allows you to upload and download files.
This plugin defines global FileTransfer, FileUploadOptions Constructors.
Although in the global scope, they are not available until after the deviceready event.
Installation
cordova plugin add cordova plugin add cordova-plugin-file-transfer


    2.   org.apache.cordova.file
          This plugin implements a File API allowing read/write access to files residing on the    device.
           Installation
cordova plugin add cordova-plugin-file
3.Implementation
Download the latest stable ngCordova release and copy ng-cordova.js to your www/js directory.  With the library in place, you now need to add it to your projects index.html file similar to the following:


<!DOCTYPE html>
<html>
 <head>
   <meta charset="utf-8">
   <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">


   <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
   <link href="css/ionic.app.css" rel="stylesheet">
   -->


   <!-- ionic/angularjs js -->
   <script src="lib/ionic/js/ionic.bundle.js"></script>
   
    <!-- ng-cordova  -->
   <script src="js/ng-cordova.js"></script>


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


   <!-- your app's js -->
   <script src="js/app.js"></script>
   <script src="js/FileTransferController.js"></script>
 </head>
 <body ng-app="starter">


   <ion-pane>
     <ion-header-bar class="bar-stable">
       <h1 class="title">Ionic Blank Starter</h1>
     </ion-header-bar>
     <ion-content ng-controller="MyCtrl">
      <button class="button" ng-click="downloadFile()">DownloadFile</button>
      <button class="button" ng-click="uploadFile()">UploadFile</button>
     </ion-content>
   </ion-pane>
 </body>
</html>
Now need to add it to your projects app.js file similar to the following:
var app = angular.module('starter', ['ionic', 'ngCordova'])
.run(function($ionicPlatform) {
 $ionicPlatform.ready(function() {
   if(window.cordova && window.cordova.plugins.Keyboard) {
     cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
   }
   if(window.StatusBar) {
     StatusBar.styleDefault();
   }
 });
})


Now need to add it to your projects FileTransferController.js file similar to the following
Here I Use php server code to upload or download file


app.controller('MyCtrl', function($scope, $timeout, $cordovaFileTransfer) {
 $scope.downloadFile = function() {
   var url = "http://your_ip_address/images/my.jpg";
   var filename = url.split("/").pop();
   alert(filename);
   var targetPath = cordova.file.externalRootDirectory + filename;
   var trustHosts = true
   var options = {};
   alert(cordova.file.externalRootDirectory);
   $cordovaFileTransfer.download(url, targetPath, options, trustHosts)
     .then(function(result) {
       // Success!
       alert(JSON.stringify(result));
     }, function(error) {
       // Error
       alert(JSON.stringify(error));
     }, function (progress) {
       $timeout(function () {
         $scope.downloadProgress = (progress.loaded / progress.total) * 100;
       })
     });
}
$scope.uploadFile = function() {
   var url = "http://your_ip_address/uploads/upload.php";
   //target path may be local or url
   var targetPath = "http://your_ip_address/images/my.jpg";
     var filename = targetPath.split("/").pop();
       var options = {
           fileKey: "file",
           fileName: filename,
           chunkedMode: false,
           mimeType: "image/jpg"
       };
       $cordovaFileTransfer.upload(url, targetPath, options).then(function(result) {
           console.log("SUCCESS: " + JSON.stringify(result.response));
           alert("success");
           alert(JSON.stringify(result.response));
       }, function(err) {
           console.log("ERROR: " + JSON.stringify(err));
           alert(JSON.stringify(err));
       }, function (progress) {
           // constant progress updates
           $timeout(function () {
          $scope.downloadProgress = (progress.loaded / progress.total) * 100;
        })
       });
   }
});


3.Server Side Implementation In PHP
Here is what the outer structure of your Ionic project will look like:
├── wamp     // wamp directory
 ├── www    // www directory
      ├── images  //root directory to stored your images for dowanload
      ├── uploads   //root directory to your php project file upload
          ├── uploaddata  //uploaddata directory to upload file
├── upload.php     // php code to upload file
├── index.php    // test code to upload file in browser
Now need to add it to your uploads  projects index.php file similar to the following:
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
   Select image to upload:
   <input type="file" name="file" id="file">
   <input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>


Now need to add it to your uploads  projects upload.php file similar to the following:
<?php
if(!isset($_FILES['file']) || ($_FILES['file']['tmp_name'] == ''))
       echo "Please choose a file.";
   else {
       $uploadfile =  $_FILES['file']['name'];
       $uploadfilename = $_FILES['file']['tmp_name'];  
   }
$location = 'uploaddata/';
if(move_uploaded_file($uploadfilename, $location.$uploadfile)){
echo 'File uploaded..';
} else {
echo 'Error to upload..';
}
?>


Download source code from here.
       



Comments

  1. Great tutorial! Would you consider including the final code (both server and Ionic) at the end of the tutorial?

    Thanks for your help!

    ReplyDelete
  2. I have Update my tutorial please check it and download code from https://github.com/santoshshinde2012/FileTransfer_Upload

    ReplyDelete
  3. I was getting 401 error while trying to download based on the example. I added plugin cordova-plugin-whitelist to the application. Then it worked fine.

    ReplyDelete
  4. Which cordova-plugin-file-transfer version are you use?
    Did you have error with code 3? FileTransferError equals:
    body: null
    code: 3
    exception: null
    http_status: 401
    source: "http://login.messme.me:8081/blog/eaa60665-2ab3-49cf-93cb-3c76136cc434"
    target: "file:///data/data/com.ionicframework.messme435314/files/audio.3gpp"

    ReplyDelete
  5. Thank You Santosh its working perfectly fine

    ReplyDelete
  6. I have used the same code. But getting some errors at $cordovaFileTransfer

    .controller('BeforeArrivalCtrl', function ($cordovaFileTransfer)

    In this controller no code is being processed. WHen I remove $cordovaFileTransfer then my code works fine.

    I have added the mentioned plugins also. But not working

    ReplyDelete
  7. thanks alot man you save my day

    ReplyDelete
  8. how to take image from the mobile device??

    ReplyDelete
    Replies
    1. May be it help you
      https://forum.ionicframework.com/t/working-example-to-upload-photo-from-camera-or-galley-with-ngcordova/12852

      Delete
  9. this was only works in localhost..when i tried it in mobile it not work...got error in alert

    ReplyDelete
  10. Please host your php code on server and replace your ip address with your hosted address

    ReplyDelete
  11. i want to transfer file from application server to mobile using phonegap ,is it achievable or not...need your help...thanks in advance

    ReplyDelete
  12. You directly run this application on mobile , and please elaborate your requirement .

    ReplyDelete
  13. pushnotifications not working fine ..please help ,what to add to work that links fine..Thanks in Advance

    ReplyDelete
  14. hi, iam trying to work with pushnotifications in this downloaded code,but unable to work bcz no code is there in the demo\www\app/pushnotifications folder,how to make it work fine...Thanks in Advance

    ReplyDelete
  15. how to download images or videos from external url and store in iPhone's gallery or in New 'myImages' folder? Actually could you tell me what is the directory path for iOS, plz. Thank you.

    ReplyDelete
    Replies
    1. Please check official documentation for cordova file plugin for ios parameter from http://ngcordova.com/docs/plugins/file/

      Delete
  16. thankyou....... its so helpful for me

    ReplyDelete
  17. very helpful, thanks very much :-)

    ReplyDelete
  18. Hi,how to download file in mobile from server ?

    ReplyDelete

Post a Comment

Popular posts from this blog

What exactly means MVW design pattern ?

What is a MVW framework? The abbreviation stands for 'Model - View - Whatever'.  Well there are many different JavaScript frameworks available , all invented for the same purpose. They all try to separate the presentation logic from the business logic where JavaScript holds the model and logic, and html the presentation layer. Quick overview : You can change the model without changing the view and vice-versa Unit testing is easy These are the core benefits of using such a framework. By separating presentation and business logic changes to the code are easier to implement and take less time. Another benefit is that code can be reused from a controller thus saving more time. Angularjs makes the code also shorter in comparison to other frameworks, which improves code stability. Less code means minor potential for bugs. For several years +AngularJS was closer to MVC (or rather one of its client-side variants), but over time and thanks to many refactorings

Steps To Create Cordova Plugin

Introduction A plugin is a package of injected code that allows the Cordova webview within which the app renders to communicate with the native platform on which it runs. Plugins comprise a single JavaScript interface along with corresponding native code libraries for each supported platform. Due to following reason, we will go for plugin development To get the native capabilities of the device in the cordova based app Build the common functionality across the number of Cordova application(Reusability) Prerequisites For the creation of plugin you need to install plugman . npm install -g plugman Plugin Structure Decide Plugin ID & Name The plugin ID should be unique Plugin name should follow the convention “cordova.plugin.[your.plugin.name]” Create the structure Use the following command to create the plugin with plugin ID “cordova.plugin.test” and name “Test”. plugman create --name Test --