This is a snippet for uploading images using the html5 file input on the device. This will capture the image selected in base64 format, so it can be easly uploaded to a backend.
It should trigger something like this:
...
<img ng-src="imagesrc" class="avatar" ng-click="uploadProfilePic()"/>
<button class="button button-primary" ng-click="uploadProfilePic()">Change Picture</button>
<input type="file" accept="image/*" id="upload" />
...
.controller('ProfileCtrl', function($scope, $q, $http) {
$scope.uploadProfilePic = function () {
var $input = angular.element(document.getElementById('upload'));
$input[0].click();
$input.on('change', function (e) {
var reader = new FileReader();
// Listening when loading ends ...
reader.onloadend = function (_e) {
// Result in base64
var base64img = _e.target.result;
// Upload to backend
uploadImg(base64img)
.then(function (result){
console.log("Image uploaded!", result);
// We apply it to our view image
$scope.imagesrc = result.img_url;
$scope.$apply();
}, function(error) {
alert("Could'nt upload image!", error);
});
// Debug purposes (if you want to see the image right away, before it's uploaded)
// $scope.imagesrc = base64img;
// $scope.$apply();
};
file = e.target.files[0];
if(file){
// we read the data from our selected image to get the Base64
reader.readAsDataURL(file);
}
});
};
function uploadImg (file) {
var defer = $q.defer();
var request = {
method: 'POST',
... // Upload parameters for your backend service.
};
$http(request)
.then(function(response) {
defer.resolve(response);
}, function(error) {
defer.reject(error);
});
return defer.promise;
}
});
.avatar {
height: 128px;
width: 128px;
border-radius: 50%;
border: 3px solid #fff;
box-shadow: 0 4pt 10pt rgba(0,0,0,1);
}
#upload {
display: none;
}