File upload not working in AngularJS

Issue

Here’s my code in my controller file that is suppose to grab the values of each input element (name, price, date, image) and push it into an array of objects…

$scope.addBook = function(name, price, date, image) {

        name = $scope.name;
        price = $scope.price;
        date = $scope.date;
        image = $scope.image;

      $scope.products.push({
            name: name,
            price: price,
            pubdate: date,
          cover: image,
            likes: 0,
            dislikes: 0
        });


      };

This is what I have in my index.html

      <form>


        <input id="name" ng-model="name" type="text" placeholder="Book Title">
        <input id="price" ng-model="price" type="text" placeholder="Enter Book Price">
        <input id="date" ng-model="date" type="date" placeholder="Publication Date">

        <input type="file" ng-model="image"/>

        <input ng-click="addBook()" type="submit" value="Submit">
      <form>

I’m not sure why the code does not work. I do not get an error or anything when I the addBook() function is executed.

Solution

Here is how ng-file-upload works

<!--Upload on form submit or button click-->
<form ng-app="fileUpload" ng-controller="MyCtrl" name="form">
    Single Image with validations
    <div class="button" ngf-select ng-model="file" name="file" ngf-pattern="'image/*'"
    ngf-accept="'image/*'" ngf-max-size="20MB" ngf-min-height="100"
    ngf-resize="{width: 100, height: 100}">Select</div>
    <button type="submit" ng-click="submit()">submit</button>
</form>

Controller

app.controller('MyCtrl', ['$scope', 'Upload', function ($scope, Upload) {
    // upload later on form submit or something similar
    $scope.submit = function() {
        if ($scope.form.file.$valid && $scope.file) {
            $scope.upload($scope.file);
        }
    };
    $scope.upload = function (file) {
        Upload.upload({
            url: 'upload/url',
            data: {file: file, 'username': $scope.username}
        }).then(function (resp) {
            console.log('Success ' + resp.config.data.file.name + 'uploaded. 
            Response: ' + resp.data);
        }, function (resp) {
            console.log('Error status: ' + resp.status);
        }, function (evt) {
            var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
            console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
        });
    };
}]);

take a look at the documentation

Answered By – Amadou Beye

Answer Checked By – David Marino (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.