1

我正在为我的 Angular 项目使用 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 > 0) 行:

Uncaught TypeError: Cannot read property 'length' of null

并且文件选择窗口从来没有出现过,我第三次点击上传按钮它又可以正常工作了,第四次没有,等等...... ng-file-upload的版本是9.0.4,是这个bug lib 尚未修复还是我犯了一些错误?谢谢。

4

1 回答 1

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

查看文档

于 2015-10-04T16:46:26.470 回答