我正在尝试使用新的@ angular / fire 5.1.0
查看使用AngularFireStorage上传到Firebase的图像。
我曾经能够在angularfire2中使用task.downloadURL()
“如果我错了,请纠正我,但现在我必须使用afStorage.getDownloadURL()
请您协助我正确设置imageUrl。
import { AngularFireStorage, AngularFireStorageReference, AngularFireUploadTask } from '@angular/fire/storage'
....
downloadURL: Observable<string>;
imageUrl: string;
....
async onGetFromGallery(){
try{ ....
const imageData = await this.camera.getPicture(options);
const image = 'data:image/jpeg;base64,' + imageData;
const id = Math.random().toString(36).substring(2);
const user = this.authenticatorService.getUser();
this.ref = this.afStorage.ref(user.uid + '/images/categories/'+id);
this.task = this.ref.putString(image, 'data_url');
//--- Previously:angularfire2:
// this.downloadURL = this.ref.getDownloadURL();
// this.downloadURL.subscribe(url=> this.imageUrl=url);
//--- now replaced by this.ref.getDownloadURL()...
//My Attempt - unable to getDownloadUrl?
this.task
.snapshotChanges().toPromise().then(_ =>
{
this.ref.getDownloadURL().toPromise().then(res => {
console.log('URL: ', res);
this.imageUrl = res;
});
})
} catch(e) {
console.error(e);
this.errorMessage = JSON.stringify(e);
}
}
查看摘录:
<img [src]="imageUrl" style="width:100%;">
package.json摘录:
“ @ angular / compiler-cli”:“ 5.2.11”,
“ @ angular / fire”:“ ^ 5.1.0”,
“ firebase”:“ ^ 5.5.9”,
“ cordova-android”:“〜7.0.0”,
谢谢。
最佳答案
代码中还进行了其他一些小的结构更改,而不仅仅是重命名该方法。
在标题为“监视上载百分比”的部分下查看the example code in the official AngularFire2 docs。具体来说,示例上传功能包括:
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()
}
更具体地说,该功能的这一部分,即监听器。
// get notified when the download URL is available
task.snapshotChanges().pipe(
finalize(() => this.imageUrl = fileRef.getDownloadURL() )
)
.subscribe()
上传完成后将触发,并使用URL填充
this.downloadURL
变量。您已经定义了fileRef
,在您的代码中仅定义了ref
,因此以下内容应该可以正常工作,但未经测试: // get notified when the download URL is available
task.snapshotChanges().pipe(
finalize(() => this.downloadURL = ref.getDownloadURL() )
)
.subscribe()
关于javascript - @ angular/fire AngularFireStorage getDownloadUrl(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53480280/