无法访问控制器中上传的文件

Not able to access uploaded files in controller

帮助我解决问题的最新代码

    $scope.uploadedFiles = [];

    $scope.upload = function(files) {
        $scope.uploadedFiles = files;
        angular.forEach(files, function(file) {
            if (file && !file.$error) {
                if($scope.uploadedFiles.indexOf(file) == -1) {
                  $scope.uploadedFiles.push(file);
                }
                file.upload = Upload.upload({
                  url: 'uploader',
                  file: file,
                  userId: $scope.user._id
                });

                file.upload.then(function (response) {
                  $timeout(function () {
                    file.result = response.data.id;
                  });
                }, function (response) {
                  if (response.status > 0)
                    $scope.errorMsg = response.status + ': ' + response.data;
                });

                file.upload.progress(function (evt) {
                  file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
                });
          }   
        });
        console.log($scope.uploadedFiles);

    }

    $scope.removeUploadedFile = function(files, idx) {
      files.splice(idx, 1);
      console.log($scope.uploadedFiles);
      $scope.uploadedFiles = files;
      console.log($scope.uploadedFiles);
    }
         .form-group
          .btn.btn-default.btn-file
           i.fa.fa-paperclip
           |  Attach Files
           input(type='file', ngf-select='upload($files)',accept="text/plain, image/*", ng-model="files", ngf-multiple="true", ngf-max-size='10000000', ngf-keep="true", ngf-keep-distinct="true")
          p.help-block Max. 1MB
          br
          ul#files(ng-repeat="f in files", style='list-style-type: none; padding:0; margin:0;')
           li
            div
             {{f.name}}
             .pull-right
              {{f.size | bytes}}   #[i.fa.fa-close(ng-click="removeUploadedFile(files, $index)")]
            div.progress(ng-show="f.progress >= 0")
             div(style="width:{{f.progress}}%", ng-bind="f.progress + '%'") 

我正在使用 ng-file-upload 处理文件上传。一切正常,除了我无法在我的控制器中访问 files

这是我的控制器代码:

$scope.upload = function(files) {
    uploadedFiles = files;
    console.log($scope.files);
    angular.forEach(files, function(file) {
        if (file && !file.$error) {
            file.upload = Upload.upload({
              url: 'uploader',
              file: file,
              userId: $scope.user._id
            });

            file.upload.then(function (response) {
              $timeout(function () {
                file.result = response.data.id;
              });
            }, function (response) {
              if (response.status > 0)
                $scope.errorMsg = response.status + ': ' + response.data;
            });

            file.upload.progress(function (evt) {
              file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
            });
      }   
    });

    console.log(uploadedFiles);
}

$scope.removeUploadedFile = function(files, idx) {
  console.log(files);
  files.splice(idx, 1);
  uploadedFiles = files;
}

还有我的 html 代码:

                                .form-group
                                    .btn.btn-default.btn-file
                                        i.fa.fa-paperclip
                                        |  Attach Files
                                        input(type='file', name='attachment', ngf-select='upload($files)',accept="text/plain, image/*", ng-model="files", ngf-multiple="true", ngf-max-size='10000000', ngf-keep="true", ngf-keep-distinct="true")
                                    p.help-block Max. 1MB
                                    br
                                    //- ul(ng-repeat='file in uploadedFiles', style='list-style-type: none; padding:0; margin:0;')
                                    ul#files(ng-repeat='f in files', style='list-style-type: none; padding:0; margin:0;')
                                        li
                                            div
                                                {{f.name}}
                                                .pull-right
                                                    {{f.size | bytes}}   #[i.fa.fa-close(ng-click="removeUploadedFile(files, $index)")]
                                            div.progress(ng-show="f.progress >= 0")
                                                div(style="width:{{f.progress}}%", ng-bind="f.progress + '%'") 

如果我打印 $scope.files,它什么也不会打印。

任何我做错的地方都将不胜感激。

更新:

为什么我需要访问 $scope.files?文件上传功能工作正常,但我需要将上传的文件 ID 传递到我的后端系统,以便将该 ID 保存在我的数据库中。现在要做到这一点,我需要一些包含更新文件列表的 $scope 变量。因为我允许用户删除上传的文件,所以我需要一些 $scope 变量来更新最新的有效上传文件列表。让我知道是否仍然不清楚。

我猜 ng-file-upload 在调用 ngf-select 函数后更新了范围值。

尽管我不明白为什么您要在上传函数中访问 $scope.files,即使您可以通过函数参数访问相同的值。 如果你坚持使用 $scope.files,你可以用 $timeout.

包装你的逻辑

示例代码如下。

$scope.upload = function(){
    console.log('Outside $timeout :', $scope.files);
    $timeout(function(){
        console.log('Inside $timeout :', $scope.files);
    });
}

jsfiddle is here.

我的建议:

  1. 当你需要在ngf-select函数中访问files时,我建议只使用函数参数。

  2. 当你想在其他函数中访问files时,你可以直接访问$scope.files

已编辑:

如果你想在每次添加新文件时都更新文件,你需要在函数范围外设置$scope.files并将新文件推送到$scope.files数组$scope.files.push(file);:

$scope.files = [];

function uploadFiles(files) {
    angular.forEach(files, function (file) {
        $scope.files.push(file);

        if (file && !file.$error) {
            file.upload = Upload.upload({
              url: 'https://angular-file-upload-cors-srv.appspot.com/upload',
              file: file
            });

            file.upload.then(function (response) {
              $timeout(function () {
                file.result = response.data;
              });
            }, function (response) {
              if (response.status > 0)
                $scope.errorMsg = response.status + ': ' + response.data;
            });

            file.upload.progress(function (evt) {
              file.progress = Math.min(100, parseInt(100.0 * 
                                       evt.loaded / evt.total));
            });
        }   
    });

ngf-keep 存在一些问题,已在版本 7.0.12 中修复。 您原来的 post 现在应该可以使用了,或者您可以按照以下步骤操作:https://jsfiddle.net/danialfarid/e7x1xs4a/

<button ngf-select="uploadFiles($files)" ngf-keep="true" multiple>Select Files</button>

$scope.uploadFiles = function(files) {
    $scope.files = files;
    console.log(files);
    angular.forEach(files, function(file) {
        if (file && !file.$error) {
            file.upload = Upload.upload({
              url: 'https://angular-file-upload-cors-srv.appspot.com/upload',
              file: file
            });

            file.upload.then(function (response) {"success"
            }, function (response) {"error"});

            file.upload.progress(function (evt) {"progress"});
        }   
    });
}