3

我正在使用angular-file-uploaddanialfarid 的模块(https://github.com/danialfarid/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
4

1 回答 1

4

循环内的闭包很棘手。关闭循环变量将始终获得最后一个值(例如,请参阅这个问题- 并在谷歌上搜索更多理论/细节)。您想要的是在循环中调用另一个函数:

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;
}
于 2014-06-10T10:43:36.153 回答