【问题标题】:How to handle ProgressBar while image is uploading to firebase图片上传到firebase时如何处理ProgressBar
【发布时间】:2019-05-30 18:05:47
【问题描述】:

我正在将图像上传到 Firebase 存储。但我无法在我的代码中处理 ProgressBar。

组件

onSubmit(){
      const fileRef = this.storage.ref(filepath)
      this.storage.upload(filepath,this.selectedImage).snapshotChanges().pipe(
        finalize(() => {
          fileRef.getDownloadURL().subscribe((url) => {
            this.upSvc.insertImageDetails(this.daydetails.value);
            this.toaster.success("Submitted successfully")
            this.router.navigate(['../Home'],{relativeTo:this.activatedroute})
          })
        }),
      ).subscribe()
}

HTML

<div class="progress">
   <div class="progress-bar progress-bar-animated" [ngStyle]="{ 'width': progress + '%' }"></div>
</div>
Progress: {{progress}}% Complete

【问题讨论】:

    标签: angular progress-bar


    【解决方案1】:

    this.storage.upload() 返回一个AngularFireUploadTask。 这个任务有一个percentageChanges() observable,可以输出你需要的东西。

    类似

    
    uploadProgress$: Observable<number>
    
    onSubmit(){
          const fileRef = this.storage.ref(filepath)
          const task = this.storage.upload(filepath,this.selectedImage)
    
          this.uploadProgress$ = task.percentageChanges()
    
          task.snapshotChanges().pipe(
            finalize(() => {
              fileRef.getDownloadURL().subscribe((url) => {
                this.upSvc.insertImageDetails(this.daydetails.value);
                this.toaster.success("Submitted successfully")
                this.router.navigate(['../Home'],{relativeTo:this.activatedroute})
              })
            }),
          ).subscribe()
    }
    
    <div class="progress" *ngIf="uploadProgress$ | async as progress">
       <div class="progress-bar progress-bar-animated" [ngStyle]="{ 'width': progress + '%' }"></div>
    </div>
    

    【讨论】:

      【解决方案2】:

      通过 Firebase SDK

      您可以在要上传文件的节点上捕获state_changed 事件,然后在该节点上调用snapshotChanges() 以获取计算当前文件上传进度所需的数据。 这是一个例子

      var uploadTask = storageRef.child('images/rivers.jpg').put(file);
      
      // Register three observers:
      // 1. 'state_changed' observer, called any time the state changes
      // 2. Error observer, called on failure
      // 3. Completion observer, called on successful completion
      uploadTask.on('state_changed', function(snapshot){
        // Observe state change events such as progress, pause, and resume
        // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
        var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
        console.log('Upload is ' + progress + '% done');
        switch (snapshot.state) {
          case firebase.storage.TaskState.PAUSED: // or 'paused'
            console.log('Upload is paused');
            break;
          case firebase.storage.TaskState.RUNNING: // or 'running'
            console.log('Upload is running');
            break;
        }
      }, function(error) {
        // Handle unsuccessful uploads
      }, function() {
        // Handle successful uploads on complete
        // For instance, get the download URL: https://firebasestorage.googleapis.com/...
        uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
          console.log('File available at', downloadURL);
        });
      }); 
      

      您可以找到更多信息here

      通过 AngularFire2

      您可以使用由upload()返回的AngularFireUploadTask

      然后你可以调用percentageChanges(),这是一个Observable,它会发出上传进度的百分比

      uploadProgress:Observable<number>;
      uploadTask: any;
      onSubmit(){
        const fileRef = this.storage.ref(filepath)            
      
        this.uploadTask = this.storage.upload(filepath,this.selectedImage).snapshotChanges().pipe(
          finalize(() => {
            fileRef.getDownloadURL().subscribe((url) => {
              this.upSvc.insertImageDetails(this.daydetails.value);
              this.toaster.success("Submitted successfully")
              this.router.navigate(['../Home'],{relativeTo:this.activatedroute})
            })
          })).subscribe()
         this.uploadProgress = this.uploadTask.percentageChanges();
          }
      

      在您的 HTML 中:

      <div class="progress">
         <div class="progress-bar progress-bar-animated" [ngStyle]="{ 'width': progress + '%' }"></div>
      </div>
      
      Progress: {{ uploadProgress | async }}% Complete
      

      您可以找到更多信息here

      【讨论】:

        【解决方案3】:

        我不得不在这里重构其他解决方案,以便为我提供可以作为服务工作的东西:

        storage.service.ts

        import { Injectable } from '@angular/core';
        import { AngularFireStorage } from '@angular/fire/storage';
        import { LogService } from './log.service';
        import { Observable, Subject, Subscription } from 'rxjs';
        import { finalize } from 'rxjs/operators';
        
        @Injectable({
          providedIn: 'root'
        })
        export class StorageService {
        
          uploadProgress: Observable<number>;
          uploadProgressSubscription: Subscription;
          private uploadProgressSubject = new Subject<any>();
        
          constructor(
            private storage: AngularFireStorage,
            private logService: LogService,
          ) { }
        
          //private logService: LogService
            log(...data){
            this.logService.log("storage",...data);
          }
        
          fileToStorage = (file,basepath) => { 
            
            return new Promise((resolve,reject) => {
              this.log("file",file);
              this.log("basepath",basepath);
              const filePath = `${basepath}/${file.name}.png`;
              const storageRef = this.storage.ref(filePath);
              const uploadTask = this.storage.upload(filePath, file);
        
              uploadTask.percentageChanges()
                .subscribe((percent) => {
                  this.uploadProgressSubject.next(percent);
              })
        
              uploadTask.snapshotChanges().pipe(
                finalize(() => {
                  storageRef.getDownloadURL().subscribe((downloadURL) => {
                    this.log("downloadURL",downloadURL);
                    resolve(downloadURL);
                  });
                })
              ).subscribe((task) => {},(error) => {reject(error)});
            })
          }
        
          uploadProgressObservable(){
            return this.uploadProgressSubject.asObservable();
          }
        
        }
        

        然后在文件中打算跟踪进度:

        // init the required subscription
        ngOnInit() {
            this.stepsArray = [];
            this.setImageUploadProgressSubscription()
          }
        
          ngOnDestroy(){
            this.imageUploadProgressSubscription.unsubscribe()
          }
        
          setImageUploadProgressSubscription(){
            if(!this.imageUploadProgressSubscription){
              this.imageUploadProgressSubscription = this.storageService.uploadProgressObservable()
              .subscribe((progress) => {
                this.imageProgress = progress / 100;
              })
            }
          }
        

        将文件添加到存储中:

        let mainImageUrl = await this.storageService.fileToStorage(image,"Pictures");
        

        处理进度条显示的 HTML

        <div *ngIf="submitting">
          <ion-popover>
            <ion-card>
              <ion-card-title>
                <ion-progress-bar value="{{progress}}"></ion-progress-bar>
              </ion-card-title>
              <ion-card-content>{{progresscontent}}</ion-card-content>
              <ion-card-subtitle>
                <ion-progress-bar value="{{imageProgress}}"></ion-progress-bar>
              </ion-card-subtitle>
            </ion-card>
          </ion-popover>
        </div>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-06-24
          • 1970-01-01
          • 1970-01-01
          • 2017-12-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多