我正在尝试使用新的@ 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”,
谢谢。
答案 0 :(得分:4)
代码中还进行了其他一些小的结构更改,而不仅仅是重命名了方法。
在“ 监控上传百分比”部分下查看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()
上传完成后会触发,并使用网址填充this.downloadURL
变量。您已经定义了fileRef
,在您的代码中仅定义了ref
,因此以下应该可以正常工作,但未经测试:
// get notified when the download URL is available
task.snapshotChanges().pipe(
finalize(() => this.downloadURL = ref.getDownloadURL() )
)
.subscribe()