dulan
dulan

Reputation: 1604

ng-file-upload files null when clicking upload button for the second time

I'm using ng-file-upload for my angular project, here's the html code:

<div class="form-group">
    <button class="btn btn-warning" ngf-select="imagesSelected($files)" multiple="multiple" ngf-pattern="'image/*'" accept="image/jpeg,image/png">选择图片</button>
</div>

And this is my javascript code:

$scope.imagesSelected = function (files) {
    if (files.length > 0) {
        angular.forEach(files, function (imageFile, index) {
            $scope.upload = Upload.upload({
                url: '/upload_image',
                method: 'POST',
                file: imageFile,
                data: {
                    'fileName': imageFile.name
                }
            }).success(function (response, status, headers, config) {
                ...
            });
        });
    }
};

The first time when click the button to select image files, image files get uploaded immediately after selected, which is what I expected. But the second time when I click the upload button, the console has this error pointing to the if (files.length > 0) line:

Uncaught TypeError: Cannot read property 'length' of null

and the file selecting window never show up, the third time I click the upload button it works fine again, fourth time not, and so on... The version of ng-file-upload is 9.0.4, is this bug of the lib has not been fixed or did I make some mistake? Thanks.

Upvotes: 1

Views: 2857

Answers (1)

Shamal Perera
Shamal Perera

Reputation: 1671

The way you have written the code is wrong.

$scope.imagesSelected = function (files) {
    $scope.files = files;
    if (files && files.length) {
        Upload.upload({
            url: '/upload_image',
            method: 'POST',
            data: {
                files: files
            }
        }).then(function (response) {
            $timeout(function () {
                $scope.result = response.data;
            });
        }, function (response) {
            if (response.status > 0) {
                $scope.errorMsg = response.status + ': ' + response.data;
            }
        }, function (evt) {
            $scope.progress = 
                Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
        });
    }
};

See Documentation

Upvotes: 1

Related Questions