如何获取Firebase文件存储的下载网址

时间:2018-08-29 06:42:04

标签: javascript angular firebase

我无法理解下载URl的过程,有人可以将其分解为我吗? 所以我在这里有这个上传组件:

import { Component, OnInit } from '@angular/core';
import { AngularFireStorage, AngularFireUploadTask } from 
'angularfire2/storage';
import { AngularFirestore } from 'angularfire2/firestore'; 
import { Observable } from 'rxjs/Observable';
import { tap, filter, switchMap } from 'rxjs/operators';
import { storage } from 'firebase/storage';


@Component({
  selector: 'file-upload',
  templateUrl: './file-upload.component.html',
  styleUrls: ['./file-upload.component.scss']
})
export class FileUploadComponent {

  // Main task   
  task: AngularFireUploadTask;

  // Progress monitoring
  percentage: Observable<number>;

  snapshot: Observable<any>;

  // Download URL
  downloadURL: Observable<string>;

  // State for dropzone CSS toggling 
  isHovering: boolean;

  constructor(private storage: AngularFireStorage, private db: AngularFirestore) { }

  toggleHover(event: boolean) {
    this.isHovering = event;
  }

  startUpload(event: FileList) {
    // The File object
    const file = event.item(0)

    // Client-side validation example
    if (file.type.split('/')[0] !== 'image') { 
      console.error('unsupported file type :( ')
      return;
    }

    // The storage path
    const path = `test/${new Date().getTime()}_${file.name}`;

    // Totally optional metadata
    const customMetadata = { app: 'My AngularFire-powered PWA!' };

    // The main task
    this.task = this.storage.upload(path, file, { customMetadata })

    // Progress monitoring
    this.percentage = this.task.percentageChanges();
    this.snapshot   = this.task.snapshotChanges().pipe(
      tap(snap => {
        console.log(snap)
        if (snap.bytesTransferred === snap.totalBytes) {
          // Update firestore on completion
          this.db.collection('photos').add( { path, size: snap.totalBytes })
        }
      })
    )


    // The file's download URL
    this.downloadURL = this.task.downloadURL(); 
    console.log(this.downloadURL)

  const ref = this.storage.ref(path);
  this.task = ref.put(file, {customMetadata});

  this.downloadURL = this.task.snapshotChanges().pipe(
    filter(snap => snap.state === storage.TaskState.SUCCESS),
    switchMap(() => ref.getDownloadURL())
  )
  console.log(this.downloadURL);
}

  // Determines if the upload task is active
  isActive(snapshot) {
    return snapshot.state === 'running' && snapshot.bytesTransferred < snapshot.totalBytes
  }}

我尝试以一种假定的方式来获取下载URL,但是它是空的,我已经看到了完成它的其他方法,但似乎无法正确完成。即使使用snapshot.downloadURL,下载URL始终为null。 以下是  package.json:

{
  "name": "storage-app",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^6.0.3",
    "@angular/common": "^6.0.3",
    "@angular/compiler": "^6.0.3",
    "@angular/core": "^6.0.3",
    "@angular/forms": "^6.0.3",
    "@angular/http": "^6.0.3",
    "@angular/platform-browser": "^6.0.3",
    "@angular/platform-browser-dynamic": "^6.0.3",
    "@angular/platform-server": "^6.0.3",
    "@angular/router": "^6.0.3",
    "angularfire2": "5.0.0-rc.6",
    "core-js": "^2.5.4",
    "firebase": "4.12.1",
    "rxjs": "^6.0.0",
    "rxjs-compat": "^6.2.2",
    "zone.js": "^0.8.26"
  },
  "devDependencies": {
    "@angular/cli": "^6.0.8",
    "@angular/compiler-cli": "^6.0.3",
    "@angular/language-service": "^6.0.3",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "~6.0.60",
    "codelyzer": "^4.0.1",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.2.0",
    "tslint": "~5.7.0",
    "typescript": "~2.7.2",
    "@angular-devkit/build-angular": "~0.6.8"
  }
}

预先感谢

4 个答案:

答案 0 :(得分:2)

您可以从存储参考中检索下载网址:

loading = false;

uploadFile(event) {

    this.loading = true;

    const file = event.target.files[0];
    // give it a random file name
    const path = Math.random().toString(36).substring(7); 
    const storageRef = this.storage.ref(path);
    const task = this.storage.upload(path, file);

    return from(task).pipe(
      switchMap(() => storageRef.getDownloadURL()),
      tap(url => {
          // use url here, e.g. assign it to a model
      }),
      mergeMap(() => {
          // e.g. make api call, e.g. save the model 
      }),
      finalize(() => this.loading = false)
    ).subscribe(() => {
      // success
    }, error => {
      // failure
    });
  }

我正在使用angularfire 5.0.0-rc.11

答案 1 :(得分:0)

这是一个简单的示例,可帮助您了解操作方法(摘自AngularFire2 GitHub):

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

constructor(
  private storage: AngularFireStorage
) {
}

uploadFile(event) {
  const file = event.target.files[0];
  const filePath = 'files';
  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()
}

这是此模板:

<input type="file" (change)="uploadFile($event)" />
<div>{{ uploadPercent | async }}</div>
<a [href]="downloadURL | async">{{ downloadURL | async }}</a>

正在发生的事情:

我们正在处理文件输入的change事件。完成后,我们将上传文件。然后,我们通过调用ref并将其路径传递到文件来在Firebase存储上创建文件引用。这将在以后检索文件下载URL时有所帮助。

此后,我们通过在storage上调用upload并向其传递文件路径和要上传的文件来创建AngularFireUplaodTask。

在此任务上,我们可以通过在上传任务上调用percentageChanges来检查文件的上传百分比。这又是一个Observable,因此我们正在使用async管道监听并在DOM上打印更改。

finalize将在完成上传任务时触发。这样一来,我们便可以通过在之前创建的getDownloadURL上调用fileRef来获取下载URL。

您可以查看此StackBlitz了解更多信息。

答案 2 :(得分:0)

现在在上载的即时结果中不再可以访问下载URL。几个月前,对Firebase客户端SDK进行了此更改。

相反,您必须调用getDownloadURL(或该JavaScript函数的任何Angular绑定)来将URL作为上传完成后的第二个请求。

答案 3 :(得分:0)

Angularfire 提供了这个超级方便的管道,getDownloadURL:

<img [src]="'users/davideast.jpg' | getDownloadURL" />

官方docs

结束。