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
- 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 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() {
//target path may be local or url
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
├── 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.
Great tutorial! Would you consider including the final code (both server and Ionic) at the end of the tutorial?
ReplyDeleteThanks for your help!
I have Update my tutorial please check it and download code from https://github.com/santoshshinde2012/FileTransfer_Upload
ReplyDeleteI 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.
ReplyDeleteWhich cordova-plugin-file-transfer version are you use?
ReplyDeleteDid 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"
Thank You Santosh its working perfectly fine
ReplyDeleteI have used the same code. But getting some errors at $cordovaFileTransfer
ReplyDelete.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
thanks alot man you save my day
ReplyDeletehow to take image from the mobile device??
ReplyDeleteMay be it help you
Deletehttps://forum.ionicframework.com/t/working-example-to-upload-photo-from-camera-or-galley-with-ngcordova/12852
this was only works in localhost..when i tried it in mobile it not work...got error in alert
ReplyDeletePlease host your php code on server and replace your ip address with your hosted address
ReplyDeletei want to transfer file from application server to mobile using phonegap ,is it achievable or not...need your help...thanks in advance
ReplyDeleteYou directly run this application on mobile , and please elaborate your requirement .
ReplyDeletepushnotifications not working fine ..please help ,what to add to work that links fine..Thanks in Advance
ReplyDeletehi, 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
ReplyDeletehow 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.
ReplyDeletePlease check official documentation for cordova file plugin for ios parameter from http://ngcordova.com/docs/plugins/file/
Deletethankyou....... its so helpful for me
ReplyDeletevery helpful, thanks very much :-)
ReplyDeleteHi,how to download file in mobile from server ?
ReplyDelete