我正在尝试使用Firebase存储和Firestore在react-js中创建上传功能。我有一个功能,可以将文件上传到Firebase存储,然后将一些数据发布到Firestore。我希望文件的网址与发送到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的代码都必须在getDownloadURL().then
回调中。
所以在您的情况下:
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;
db.collection("hittat").doc().set({
title: this.state.input.title,
amount: this.state.input.amount,
description: this.state.input.description,
url: url;
});
});
});
这也可能意味着您不再需要url
变量。
另请参阅: