第二次点击上传按钮时,ng-file-upload文件为空

时间:2015-10-04 11:44:44

标签: angularjs ng-file-upload

我正在为我的角项目使用ng-file-upload,这是html代码:

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

这是我的javascript代码:

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

第一次单击按钮选择图像文件时,图像文件会在选中后立即上传,这就是我的预期。但是当我第二次单击上传按钮时,控制台将此错误指向if(files.length&gt; 0)行:

Uncaught TypeError: Cannot read property 'length' of null

并且文件选择窗口永远不会显示, 我第三次点击上传按钮它再次正常工作,第四次没有,依此类推...... ng-file-upload的版本是9.0.4,这个lib的bug还没有修复,或者我犯了一些错误?感谢。

1 个答案:

答案 0 :(得分:1)

你编写代码的方式是错误的。

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

请参阅Documentation