Seegatesite.com – An easy way to create a button download files from url using ionic framework. Continuing my previous tutorial How to Create Android Image Gallery with Ionic Framework and Web Services, if we want to create wallpaper application on the mobile app then it should add features download button. ngCordova has provided plugin to perform file transfer in ionic framework.
Table of Contents
What is ngCordova ?
ngCordova is a collection of scripts which are summarized for ease of function calls that exist in PhoneGap / Cordova. It gives you simple AngularJS wrappers , where you can take a picture, scan a barcode, download file, upload a file and much more with just a few lines of code.
ngCordova Installation Guide
It has been discussed in detail how to install ngCordova on the ngCordova official site. I’m just a little review of their main code. Instructions how to install ngcordova :
- You can install ngCordova through a bower or directly download the js file.
bower install ngCordova
or
- Include ng-cordova.js or ng-cordova.min.js in your index.html file before cordova.js
- Add the plugin to your project using the Cordova CLI
cordova plugin add plugin-name
- Inject as an Angular dependency
angular.module('myApp', ['ngCordova'])
- Wrap each plugin call with the deviceready event – important !
$ionicPlatform.ready(function() {
$cordovaPlugin.someFunction().then(success, error);
});
Since we will make the downloading process , so we need a cordova-plugin-file-transfer plugin , here’s how to download the plugin
cordova plugin add cordova-plugin-file-transfer
For an explanation and detail usage please read from official site $cordovaFileTransfer
How to Create Download File From Url On Ionic Framework
- Create new ionic project and give name ionicdownloader.
ionic start ionicdownloader blank
- Add ngCordova plugin transfer file
cordova plugin add cordova-plugin-file-transfer
- Then Add ng-cordova script to index.html (ionicdownloader > www > index.html)123456789101112131415161718192021222324252627282930313233343536373839<!DOCTYPE html><html><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>Ionic Framework Download File</title><link href="lib/ionic/css/ionic.css" rel="stylesheet"><link href="css/style.css" rel="stylesheet"><script src="lib/ionic/js/ionic.bundle.js"></script><script src="js/ng-cordova.min.js"></script><script src="cordova.js"></script><script src="js/app.js"></script></head><body ng-app="starter"><ion-pane><ion-header-bar class="bar-stable"><h1 class="title">Download file from url</h1></ion-header-bar><ion-content ng-controller="DownloadController"><button class="button button-full button-positive" ng-click="Download()">Download it!</button><span>Download progress : {{downloadProgress}} %</span><div>{{hasil}}<img ng-src="{{mywallpaper}}" width="100%" /></div></ion-content></ion-pane></body></html>
Don’t forget to add ngCordova.js to app folder
- Edit app.js (js/app.js) and copy the following script12345678910111213141516171819202122232425262728293031323334angular.module('starter', ['ionic','ngCordova']).run(function($ionicPlatform) {$ionicPlatform.ready(function() {if(window.cordova && window.cordova.plugins.Keyboard) {cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);cordova.plugins.Keyboard.disableScroll(true);}if(window.StatusBar) {StatusBar.styleDefault();}});}).controller('DownloadController', function($scope, $cordovaFileTransfer) {$scope.Download = function () {ionic.Platform.ready(function(){var url = "http://3.bp.blogspot.com/-XchURXRz-5c/U5ApPOrPM9I/AAAAAAAADoo/YZEj4qeSlqo/s1600/Final-Fantasy-XV-Noctis-Red-Eyes.png";var filename = url.split("/").pop();var targetPath = cordova.file.externalRootDirectory + 'Pictures/' + filename;$cordovaFileTransfer.download(url, targetPath, {}, true).then(function (result) {$scope.hasil = 'Save file on '+targetPath+' success!';$scope.mywallpaper=targetPath;}, function (error) {$scope.hasil = 'Error Download file';}, function (progress) {$scope.downloadProgress = (progress.loaded / progress.total) * 100;});});}});
Explanation :
Don’t forget to add “ngCordova” syntax on angular module and “$cordovaFileTransfer” at controller to run the transfer file function on cordova.
Before we start the download process, the app must ensure that android was ready to make the download process by adding the following script
ionic.Platform.ready(function(){ ... }
$cordovaFileTransfer has the following syntax
$cordovaFileTransfer.download(url, targetPath, {}, true)
– Url : file’s url to be downloaded
– targetPath : the storage location of the downloaded file. In the experiment, using the syntax
cordova.file.externalRootDirectory
which means the files will be stored on the android storage (file:///storage/…….)– {} : an options (I never added option when downloading files)
– true : trustAllHosts (If set to true – accepts all security certificates)
After the download button press, the application will run the download process and when the download process is running, a progress bar will show the percentage of results that are downloaded on the following function
function (progress) {
$scope.downloadProgress = (progress.loaded / progress.total) * 100;
}
If you have finished adding all the above script, run the application on an emulator or build apk
ionic emulate android
or
ionic platform add android
ionic build android
If you try on the browser, downloaded files will not work and result in error “ReferenceError: cordova is not defined … ” ,because cordova can’t be run on computer’s browser
Finish, you’ve managed to create a simple android application to download images
I have not succeeded to create the stop button to stop the application when downloading files. If anyone could please help me :). Read my other ionic framework article here
I tried, but I have this issue: FileTransferError.FILE_NOT_FOUND_ERR Any help?
http://goo.gl/Nhnv6C
hope resolve your problem 🙂
Hi,
thanks for the tutorial. i tried it it downloaded successfully but on my view with a different controller i passed the $rootScope.targetfile and i output it i can see the address as
file:///mnt/sdcard/Android/data/app.simagazine.mainapp/files/SIMagissues/issue2/issue2/1.jpg
but i in the image tag the i got a blank screen i.e the image is not displaying please help
I download success, thanks, I want to creat a slide, in that, can swipe up or down for close showing image, can you help me ?
Hello Xuan Hoa,
Sorry, I never try it 🙂
error file downloading.. m getting this error
what an error ? try using on your mobile phone.. do not use simulator. CMIIW 🙂
Hi,
i tried it it downloaded successfully but It is on working for video .Can you please help me how to download video ?
this code is just for download images.
Thanks in advance
Yes this code just for download image. For video, i’ve never tried. 🙂
Hi,
can I download this project anywhere?
Greets
yes, you can
This is a great article. This method olso works for downloading: .doc, .pdf
To cancel file transfer you just need to store a reference of your FileTransfer object and call abort() on it.
Great and useful tutorial, thanks for posting 🙂
Hi
Thanks for the article. Will this work in iOS as well? Will we need to change the file’s target path?
hello shreyas,
im so sory, I have never tried on iOS 🙂
Hello author.
This is what i am getting. >>>>> Error Download file.
Do i have to create this folder, wat all changes i do have to make regarding to the PATH URL and TARGET PATH.
This article is no longer updated. sory 🙁