Skip to content

Instantly share code, notes, and snippets.

@sean-hill
Last active May 6, 2019 01:52
Show Gist options
  • Star 29 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save sean-hill/4abcec4577a44195db51 to your computer and use it in GitHub Desktop.
Save sean-hill/4abcec4577a44195db51 to your computer and use it in GitHub Desktop.
Upload service for Ionic and ngCordova
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;
}
}
})
@silsgah
Copy link

silsgah commented Jan 8, 2015

Implemented this same some time back, very good but did this on .net API

@saqueib
Copy link

saqueib commented Dec 19, 2015

$cordovaFile should be $cordovaFileTransfer with and upload method

@valix85
Copy link

valix85 commented Mar 24, 2016

What's Constants in a factory Upload declaration?

@gaspan
Copy link

gaspan commented Jun 7, 2016

is there for lan,, without connection internet?

@dslwz2008
Copy link

$cordovaFile ---> $cordovaFileTransfer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment