如何停止此功能执行多次

时间:2019-04-02 15:10:26

标签: javascript

我具有此上传功能。除了将文件上传两次之外,它运行良好。

startUpload(event: HTMLInputEvent) {
    console.log(event) // logs once

    this.tasks$ =  from([Array.from(event.target.files)]).pipe(
      map(files => files.map((file, index) => {
            console.log(file) // logs twice
            const path = `test/${index}_${file.name}`
            const customMetadata = { app: 'Angular!' }
            return this.afstorage.upload(path, file, { customMetadata });
          })
    )
    )

    this.snapshots$ = this.tasks$.pipe(
      map(files =>
        files.map(file =>
          file.snapshotChanges(),
        ),

      )
    )

    this.progresses$ = this.tasks$.pipe(
      map(files =>
        files.map(file =>
          file.percentageChanges()
        ),
      )
    )
}

如何防止其多次上传?

1 个答案:

答案 0 :(得分:0)

我认为问题出在这里

files.map((file, index) => {
  console.log(file) // logs twice
  const path = `test/${index}_${file.name}`
  const customMetadata = { app: 'Angular!' }
  return this.afstorage.upload(path, file, { customMetadata });
})

作为.map的参数提供的arrow函数将被files数组中的每个文件调用一次。

所以我的猜测是这是某种文件上传器,并且您指定了2个要上传的文件,或者可能是同一文件两次。

更新

为回应您的评论,如果您只想调用一次,例如在第一个文件中,您可以将上面的代码替换为

const index = 0;
const file = files[0];
console.log(file) // logs twice
const path = `test/${index}_${file.name}`
const customMetadata = { app: 'Angular!' }
return this.afstorage.upload(path, file, { customMetadata });

这只会上传第一个文件,但是跳过其余文件似乎不是一个好主意。

我认为您的问题有问题。您说过只希望该代码执行一次,但是如果选择了多个文件,那么在其他情况下如何上传其他文件?

相关问题