【发布时间】:2020-06-25 19:15:28
【问题描述】:
我正在尝试使用 firebase 存储和 firestore 在 react-js 中创建上传功能。我有一个功能可以将文件上传到firebase存储,然后将一些数据发布到firestore。我希望文件的 url 与去 firestore 的数据一起使用。到目前为止,我只能将 URL 记录到控制台,但我无法存储它。我在网上和 firebase 文档中查看了所有内容,但找不到在上传时存储 URL 的方法。
如果您对我可以尝试的事情有任何建议,我将不胜感激:)
publishHandler = (event) => {
event.preventDefault();
console.log(this.state.input);
let url = "";
let file = this.state.input.image;
let storageRef = firebase.storage().ref();
let uploadTask = storageRef.child("uploads/" +file.name).put(file);
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
function (snapshot) {
let progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log("upload is " + progress + " % done.");
},
function(error) {
console.log("Something went wrong..." + error);
},
function(complete) {
uploadTask.snapshot.ref.getDownloadURL().then(function (downloadURL) {
console.log(downloadURL);
// Here is where I wish I could store the downloadURL into the url variable declared earlier
url = downloadURL;
});
}
);
// Post data to firebase.
db.collection("hittat").doc().set({
title: this.state.input.title,
amount: this.state.input.amount,
description: this.state.input.description,
url: url;
});
};
【问题讨论】:
-
为什么不能存储 URL?看起来您想要存储 URL 的代码点就是您实际想要放置编写文档的现有代码的位置。
-
感谢道格的回复!因此,此代码失败,因为无法在函数内部设置变量 url。我想这与范围有关?
-
这与 Firebase API 都是异步的这一事实有关。
标签: javascript firebase google-cloud-firestore firebase-storage