Angular JS - $ q.all()跟踪单个上传进度

时间:2014-06-10 10:23:52

标签: javascript ajax angularjs q angular-file-upload

我正在使用danialfarid(https://github.com/danialfarid/angular-file-upload)的angular-file-upload模块,而且效果很好。

我已经能够在我的包装服务中集成REST调用,我实际上可以使用$q.all()上传多个图像并跟踪他们的进度。

但是,我无法正确识别我上传的单个图像,因为for循环会不断更改文件标识符。

      uploadPhotos: function (files) {

        var deferred = $q.defer()
        var queue = []

        for (var i = 0; i < files.length; i++) {
          var file = files[i];
          var up = $upload.upload({
            url: locationURI +'/photos',
            file: file,
            fileFormDataName: 'image'
          }).then(
            function (data) {
              console.log(data)
            },
            function (err) {
              console.log(err)
            },
            function(evt) {
              // progress events
              console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
            }
          )
          queue.push(up)
        }

        $q.all(queue).then(
          function (data) {
            deferred.resolve(data)
          },
          function (err) {
            deferred.reject(err)
          }
        )

        return deferred.promise
      }

这是毫不奇怪的,我得到的混淆输出:

    percent: 68 restfactory.js:359
    percent: 100 restfactory.js:359
    percent: 100 restfactory.js:359
    percent: 14 restfactory.js:359
    percent: 37 restfactory.js:359
    percent: 52 restfactory.js:359
    percent: 89 restfactory.js:359
    percent: 100 restfactory.js:359
    percent: 100 restfactory.js:359

你知道我怎么能设法得到这样的东西:

    file1 - percent: 68 restfactory.js:359
    file1 - percent: 100 restfactory.js:359
    file2 - percent: 100 restfactory.js:359

1 个答案:

答案 0 :(得分:4)

循环内的闭包很棘手。关闭循环变量将始终获得最后一个值(例如,请参阅this question - 并将其谷歌以获取更多理论/详细信息)。你想要的是在循环中调用另一个函数:

for (var i = 0; i < files.length; i++) {
    var up = doTheUpload(files[i]);
    queue.push(up);
}

并且doTheUpload()包含您的原始代码,返回承诺并使用正确的file(我知道API,我认为file.name包含文件名;适当调整):

function doTheUpload(file) {
      var up = $upload.upload({
        url: locationURI +'/photos',
        file: file,
        fileFormDataName: 'image'
      }).then(
        function (data) {
          console.log(data)
        },
        function (err) {
          console.log(err)
        },
        function(evt) {
          // progress events
          console.log(file.name + ' percent: ' + parseInt(100.0 * evt.loaded / evt.total));
        }
      );
      return up;
}