简体   繁体   中英

ng-file-upload cannot read property 'file' of undefined

I am trying to use ng-file-upload https://github.com/danialfarid/ng-file-upload

I have used the basic setup:

HTML:

<section ng-controller="MyController">

    <form 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>
                    Multiple files
                    <div class="button" ngf-select ng-model="files" ngf-multiple="true">
                        Select
                    </div>
                    Drop files:<div ngf-drop ng-model="files" class="drop-box">Drop</div>
                    <button type="submit" ng-click="submitUpload()">submit</button>
                </form>
</section>

JS:

var app = angular.module('myApp', ['ui.router', 'ngAnimate', 'ngFileUpload'], function($interpolateProvider) {
    $interpolateProvider.startSymbol('{[{');
    $interpolateProvider.endSymbol('}]}');
});

app.controller('MyController', function ($scope, RESTService) {


// upload later on form submit or something similar
$scope.submitUpload = function() {
  if ($scope.form.file.$valid && $scope.file) {
    $scope.submitUpload($scope.file);
  }
};

// upload on file select or drop
$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);
    });
};

});

I am able to select a file via the windows browser, however, when i click submit, i get the following error:

TypeError: Cannot read property 'file' of undefined

Accompanying your question with a JSFiddle would be great.

Nevertheless, these lines of code could very well cause a problem:

// upload later on form submit or something similar
$scope.submitUpload = function() {
  if ($scope.form.file.$valid && $scope.file) {
    $scope.submitUpload($scope.file);
  }
};

I believe inside the submitUpload function you should have called the upload function, because otherwise you are just recursively calling the same function with an extra argument.

If that doesn't help your issue, let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM