【问题标题】:AngularJs Uploading multiple files .then [duplicate]AngularJs上传多个文件。然后[重复]
【发布时间】:2017-12-04 15:49:50
【问题描述】:

文件的多次上传适用于 angularjs,但我无法在我的 .then() 函数中获取文件名。

这是我的上传文件功能:

    $scope.uploadFile = function(files,destinationPhp) {

    $scope.montrerLoader = true;

    for (var x=0;x<files.length;x++){

        var fd = new FormData();
        //Take the first selected file
        fd.append("file", files[x]);

        console.log(files[x].name);
        var uploadUrl = destinationPhp;

        $http.post(uploadUrl, fd, {
            withCredentials: true,
            headers: {'Content-Type': undefined },
            transformRequest: angular.identity
        }).then(function(data){ 
            $scope.montrerLoader = false;
            if(data.data.reponse=='ok'){

                if(destinationPhp=='uploadFichier.php'){
                    Notification.success('Fichier transféré!');
                    $scope.rendezVous.fichiers.push({'nom':files[x].name});
                }
            }
            else{

                Notification.error(data.data.reponse);
            }

        });

    }

};

效果很好,文件被上传到我的服务器目录,但问题是我需要这一行!:

$scope.rendezVous.fichiers.push({'nom':files[x].name});

我遇到了这个错误:

TypeError: files[x] is undefined

我已经尝试了很多方法,比如尝试将文件名放入 TEMP var 中,但它永远无法识别,或者最终总是推送相同的名称文件(这不合逻辑)。

您对上传到 $scope.rendezVous 后如何推送我的文件名有任何想法吗?

更糟糕的是这条线:

 console.log(files[x].name);

在我的萤火虫控制台中显示权限文件名!!但是只要我尝试在里面使用.then(),那就不行了!

【问题讨论】:

    标签: angularjs file-upload upload


    【解决方案1】:

    您正在 for 循环中尝试异步调用,因此您必须使用 IIFE。因此,在 IIFE 中包含 $http 将让它在 for 循环的 i 的每个值上运行,并且文件对象不会在其回调中未定义。检查此示例

    for (var index = 1; index <= files.length; index++) {      
        (function(index) {
            $timeout(function() { 
            console.log("index : "+index); 
    
             alert("file name : "+files[index-1].name);
            }, index * 500);
        })(index);
    }
    

    http://plnkr.co/edit/7ZclGB93Soq5Ce8pFmkQ?p=preview

    在这里,我使用 $timeout 添加了模拟异步调用,然后在具有 IIFE 结构的 for 循环中使用它。您可以在注释掉该异步调用的 IIFE 包装器时检查您的条件再现。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-24
      • 2015-12-04
      • 2013-06-06
      • 2015-10-18
      • 2016-01-04
      • 2016-11-04
      • 2017-02-28
      • 1970-01-01
      相关资源
      最近更新 更多