0

I'm developing the front-end of a web application with Angular and I'm new with this technology. I don't know how to pass a image to the controller and upload to the server.

I have the html for include the image:

<div class="col-lg-1">
    <label class="btn btn-default" style="margin-top: 35px">
        <i class="fa fa-picture-o" aria-hidden="true"></i>
        <input type="file" style="display: none;" accept="image/*" ng-model="image">   
    </label>
</div>

Now you can see that the image has the ng-model="image", but in the controller if I do console.log($scope.image) I get undefined.

I want to encode the image to a binary representation, put it into a JSON with other atributes and upload it to a server.

How Can I do this?

1 Answers1

1

You can do something like this

In your html

<input type="file" id="file" name="file"/>
<button ng-click="upload()">Upload</button>

In your controller

$scope.upload = function() {
    var f = document.getElementById('file').files[0];
    var r = new FileReader();
    r.onloadend = function(e) {
        var data = e.target.result;
    }
    r.readAsBinaryString(f);
}
Ajinkya Dhote
  • 1,389
  • 3
  • 13
  • 26