首页 > 解决方案 > AngularFireStorage 上传多张图片?

问题描述

我正在使用 Angularfire2 指南上传图片:https ://github.com/angular/angularfire2/blob/master/docs/storage/storage.md

我已经将其付诸实践,并且我已经设法上传,但每次操作只能上传一张图片。是否可以加载多个图像?我怎样才能实现它?

组件.ts

import { Component, OnInit } from '@angular/core';
import { AngularFireStorage } from 'angularfire2/storage';
import { Observable } from '../../../../node_modules/rxjs';
import { finalize } from 'rxjs/operators';

@Component({
selector: 'app-root',
template: `
  <input type="file" (change)="uploadFile($event)" />
  <div>{{ uploadPercent | async }}</div>
  <a [href]="downloadURL | async">{{ downloadURL | async }}</a>
`
})

export class AppComponent {

uploadPercent: Observable<number>;
downloadURL: Observable<string>;

constructor(private storage: AngularFireStorage) {}

uploadFile(event) {
  const file = event.target.files[0];
  const filePath = 'name-your-file-path-here';
  const fileRef = this.storage.ref(filePath);
  const task = this.storage.upload(filePath, file);

  // observe percentage changes
  this.uploadPercent = task.percentageChanges();
  // get notified when the download URL is available
  task.snapshotChanges().pipe(
    finalize(() => this.downloadURL = fileRef.getDownloadURL() )
 )
.subscribe()
}
}

标签: javascriptangularfirebasefirebase-storageangularfire2

解决方案


对于未来的读者,这是我在挣扎了几天后使用 Angular 8 和 Firebase 解决多张图片上传问题的方法:

export class AppComponent {

 uploadPercent: Observable<number>;
 downloadURL: Observable<string>;

 uploads: any[]; // an array that holds the uploaded image URLs and refs

constructor(private storage: AngularFireStorage) {}

uploadFile(event) {
  this.uploads = [];
  const filelist = event.target.files;

  for (const file of filelist) {
    const path = `product-images/${file.name}`;
    const ref = this.storage.ref(path);
    const task = this.storage.upload(path, file);
    //the percentage is still not 100% working as it should
    this.uploadPercent$ = task.percentageChanges();

    // for every upload we will store the image URL in this.uploads array
    const _t = task.then((f) => {
     return f.ref.getDownloadURL().then((imageURLs) => {        
      this.uploads.push(imageURLs);
    })
  });
  }

  
 //we return a promise after making sur all images has been uploaded
 return new Promise(async (resolve, reject) => {
  const run = async () => {
   if (this.uploads.length === filelist.length) {
     console.log("All image has been uploaded")
     resolve(this.uploads);
   } else {
     console.log(uploads.length + '/' + filelist.length + ' images has been uploaded..')

    //We check every 500ms if all the image has been uploaded, otherwise we try check again
     return this.delay(500).then(run);
   }
 }
 return this.delay(500).then(run);
 }) 
}


private delay(t) {
  return new Promise(resolve => {
    setTimeout(resolve, t);
  });
 }
}

我知道有一种使用 RXJS 进行异步调用的替代方法,但我无法让它工作。这就是我实现deley() 函数的原因。


推荐阅读