带有多个文件上传和进度条的ng-file-upload

时间:2015-03-04 06:51:18

标签: ruby-on-rails angularjs

我想将多个文件上传到rails服务器,并希望为每个文件显示单独的进度条。我正在使用ng-file-upload来上传文件。文件正在上传,但它只显示最后一个文件的进度,而不显示其他文件。我正在附加我的代码。请帮忙。

角度控制器代码:

$scope.upload_file = function() {

    var files = $scope.files;
    var uploadUrl = base_url+"/upload_image";
    var job_id = $scope.directive.id;
    if(current_user.role == "third_party_vendor" || current_user.role == "employee")
    {
        var source = current_user.user_login+"-"+current_user.role;   
    }
    else
    {
        var source = $scope.dataObj.source["user_login"]+"-"+$scope.dataObj.source["role"];
    }

    if(job_id === "" || job_id === undefined || files === undefined || files === ""){
        error_notification("Please select a job and a file.");
        return;
    }
    hideLoader();
    $("#upload_resume_queue").modal('show');

    var formData = new Array();
    formData['job_id'] = job_id;
    formData['context'] = "inside_page";
    formData['source'] = source;

    for (var i = 0; i < files.length; i++) {
      var file = files[i];
      console.log(file.name);
      $scope.upload = $upload.upload({
        url: uploadUrl, 
        data:{myObj: formData},
        file: file, 
      }).progress(function(evt) {
        //console.log('percent: ' +parseInt(100.0 * evt.loaded / evt.total));


                file.progress = Math.round(evt.loaded * 100 / evt.total)


      }).success(function(responseText) {
        hideLoader();
        try{
            var response = responseText;
        }catch(e){
            error_notification("Invalid Excel file Imported.");
            return;
        }
        if(response.status==='wrong_content_type')
            error_notification("Please upload a valid file format.",0);
        if(response.status==='job_application_present'){
            $scope.duplicate = true;
            $scope.jobID = job_id;
            $scope.user_id = response.user_id;
            $scope.application_id = response.application_id;
            //showModal('#duplicate_application_modal');
            error_notification("Job Application already present for this user and job.",0);
        }
        if(response.status==='invalid_email')
            error_notification("The email in the resume is an invalid one.",0);
        if(response.status==='success')
            success_notification("The uploaded resume has been parsed.",0);
      });
    }
  };

Html代码:

<input type="file" class="required file_browse" ng-file-select="" ng-model="files" multiple />

1 个答案:

答案 0 :(得分:2)

我无法测试以下内容,但我认为我发现了什么问题。

在JavaScript中,变量的作用域是函数。因此,在for循环中,您更改了.img { background-image: url(path/to/your/ima.ge); background-size: cover; } 行中file的值。最后,在var file = files[i];循环完成后,for的值是最后一个文件。

某些时候file会触发.progress事件,以通知您进度(其中一个文件)。并且您更新状态,但是,由于ng-file-upload具有最后一个文件的值,而不是您期望的那个,因此最新文件的状态正在更新。

这就是为什么只更新了最后一个文件。要解决此问题,您需要为每个file事件访问正确的file。为此,您可以使用匿名函数保留progress变量。

file

在您的代码中,可能存在与变量范围和javascript事件循环相关的其他问题。有关详细信息,请查看this