Firebase在成功将图片上传到Firebase存储后获取下载网址
问题描述:
我试图将单个图片上传到Firebase存储,然后获取其下载网址并将其分配给变量。Firebase在成功将图片上传到Firebase存储后获取下载网址
我可以成功将我的图片上传到firebase,但是我无法检索到下载网址。这是我已经尝试过的。
upload() {
let storageRef = firebase.storage().ref();
let success = false;
for (let selectedFile of [(<HTMLInputElement>document.getElementById('file')).files[0]]) {
let router = this.router;
let af = this.af;
let folder = this.folder;
let path = `/${this.folder}/${selectedFile.name}`;
var iRef = storageRef.child(path);
iRef.put(selectedFile).then((snapshot) => {
console.log('Uploaded a blob or file! Now storing the reference at', `/${this.folder}/images/`);
af.list(`/${folder}/images/`).push({ path: path, filename: selectedFile.name })
});
}
// This part does not work
iRef.getDownloadURL().then((url) => {this.image = url});
console.log('IREF IS ' + iRef)
console.log('IMAGEURL IS ' + this.image)
}
控制台日志是这些:
IREF IS gs://my-app-159520.appspot.com/images/Screen Shot 2017-08-14 at 12.19.01.png
view-order.component.ts:134 IMAGEURL IS undefined
Uploaded a blob or file! Now storing the reference at /images/images/
我一直在尝试使用IREF参考抢到下载网址,但我不断收到错误。我试图抓取网址,以便我可以将其分配给this.image变量,然后使用另一个函数将其存储在我的数据库中。
答
我想我已经想通了这一点,它似乎是工作,我意识到我必须从快照抓取然后将downloadURL和赋值给this.image像这样:
upload() {
let storageRef = firebase.storage().ref();
let success = false;
for (let selectedFile of [(<HTMLInputElement>document.getElementById('file')).files[0]]) {
let router = this.router;
let af = this.af;
let folder = this.folder;
let path = `/${this.folder}/${selectedFile.name}`;
var iRef = storageRef.child(path);
iRef.put(selectedFile).then((snapshot) => {
// added this part which as grabbed the download url from the pushed snapshot
this.image = snapshot.downloadURL;
console.log('Uploaded a blob or file! Now storing the reference at', `/${this.folder}/images/`);
af.list(`/${folder}/images/`).push({ path: path, filename: selectedFile.name })
console.log('DOWNLOAD URL IS ' + this.image)
});
}
}
然后我跑我其他功能将URL添加到数据库中,并且在预期的地方它已经没有问题了!
所以我已经上传图像到数据库,然后使用从放功能的快照,然后我指定我的可变图像:任何对快照downloadURL像这样:
this.image = snapshot.downloadURL;
我希望这能帮助别人!
“image”定义在哪里?为什么它是undefined? – onetwo12
图像在构造函数的顶部定义为图像:任何 –
我想我可能已经想通了,会更新原始文章。 –