文件上传在AngularJS中无效

时间:2017-05-19 23:49:25

标签: javascript html angularjs angular-file-upload

这是我的控制器文件中的代码,它想要获取每个输入元素的值(名称,价格,日期,图像)并将其推入对象数组中......

$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
        });


      };

这是我在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>

我不确定为什么代码不起作用。我执行addBook()函数时没有出现错误或任何错误。

1 个答案:

答案 0 :(得分:1)

以下是ng-file-upload的工作原理

<!--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>

控制器

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);
        });
    };
}]);

查看documentation