如何获取 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 也始终为空。 以下是 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"
}
}

提前致谢

您可以从存储引用中检索下载 URL:

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
});
}

我正在使用角度火5.0.0-rc.11

这里有一个简单的例子来帮助你理解如何(取自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来检查文件上传百分比。这又是一个可观察的,因此我们使用async管道在 DOM 上侦听和打印更改。

上传任务完成后,将触发finalize。那时,我们将能够通过调用之前创建的fileRef上的getDownloadURL来获取下载 URL。

你可以看看这个 堆栈闪电战 了解更多信息。

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

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

官方文档。

结束。

相关内容

最新更新