Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ynagarjuna2012/6fbd888ec0283bd22c51 to your computer and use it in GitHub Desktop.
Save ynagarjuna2012/6fbd888ec0283bd22c51 to your computer and use it in GitHub Desktop.
Ionic and ngCordova upload example
// Upload Ctrl
angular.module('starter.controllers')
.controller('UploadCtrl', function($scope, Upload){
$scope.uploadFile = function() {
Upload.fileTo(<your server api url>).then(
function(res) {
// Success
}, function(err) {
// Error
})
;
};
});
// Upload Service
angular.module('starter.services')
.factory('Upload', function($q, $cordovaCamera, $cordovaFile, Constants) {
return {
fileTo: function(serverURL) {
var deferred = $q.defer();
if (ionic.Platform.isWebView()) {
var options = {
quality: 100
, destinationType: Camera.DestinationType.FILE_URI
, sourceType: Camera.PictureSourceType.PHOTOLIBRARY
, encodingType: Camera.EncodingType.JPEG
}
$cordovaCamera.getPicture(options).then(
function(fileURL) {
var uploadOptions = new FileUploadOptions();
uploadOptions.fileKey = "file";
uploadOptions.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);
uploadOptions.mimeType = "image/jpeg";
uploadOptions.chunkedMode = false;
$cordovaFile.uploadFile(serverURL, fileURL, uploadOptions).then(
function(result) {
deferred.resolve(result);
}, function(err) {
deferred.reject(err);
})
;
}, function(err){
deferred.reject(err);
})
;
}
else {
deferred.reject('Uploading not supported in browser');
}
return deferred.promise;
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment