Skip to content

Instantly share code, notes, and snippets.

@MatiMenich
Last active December 1, 2017 18:49
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save MatiMenich/ac87ee097706bf61b831 to your computer and use it in GitHub Desktop.
Save MatiMenich/ac87ee097706bf61b831 to your computer and use it in GitHub Desktop.
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.

Upload image using html5 on ionic

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:

Image of Html5 image input

view.html

...

<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.js

.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;
}

});

styles.css

.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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment