javascript - 当我上传图像时,firebase 存储 getdownloadUrl() 将下载 url 放在 Firestore 集合中,但没有在 React JS 中设置它
问题描述
我正在尝试将图像上传到 Firebase 存储,并在成功上传后尝试将图像下载 URL 同时插入到 Firestore 集合中。
怎么做?这是上传图像工作正常但firestore不工作的代码。
dbRef = firebase.firestore().collection('stack_overflow').doc()
constructor(props) {
super(props);
this.state = {
question_id: this.dbRef.id,
question_title: '',
question_image: null,
question_image_url: '',
};
}
dataOnChange = (e) => {
const state = this.state
state[e.target.name] = e.target.value
this.setState(state)
}
handleImageOnChange = e => {
if (e.target.files[0]) {
const question_image = e.target.files[0]
this.setState(() => ({question_image}))
}
}
onSubmitData = (e) => {
e.preventDefault()
const {
question_id, question_title, question_image, question_image_url
} = this.state;
/*image upload and download*/
const uploadImage = storage.ref(`/stack_gallery/${cat_image.name}`).put(cat_image);
uploadImage.on('state_changed', (snapshot) => {
console.log("Image Upload Progress")
},
(error) => {
console.log(error);
},
/*() => {
storage.ref('quote_gallery').child(question_image.name).getDownloadURL().then(question_image_url => {
console.log(question_image_url);
this.setState({question_image_url});
})
}*/);
storage.ref('stack_gallery').child(question_image.name).getDownloadURL().then(question_image_url => {
console.log(question_image_url);
this.setState({question_image_url});
})
this.dbRef.set({
question_id, question_title, question_image_url
}).then((docRef) => {
this.add({
question_id: '',
question_title: '',
question_image_url: this.state.cat_image_url
})
}).catch((error) => {
console.error("Error Adding Document: ", error)
})
}
请检查我的代码哪里有问题以及如何解决这个问题。
解决方案
当我看到您的代码时,您将 question_image_url 保存到 this.state,并且我认为我们不必将其保存到 state,因为我们使用 state 来呈现 JSX。一旦你在回调中获得了 url,那么为什么不在回调中运行保存到 firestore 呢?而你使用了 firestore().collection().doc().set,这是错误的。您应该指明要设置的 doc_id,因为 set 是当前 doc_id 的更新功能。如果要添加新文档,则可以使用包含整个文档的集合中的添加功能。
uploadImage.on('state_changed', (snapshot) => {
console.log("Image Upload Progress")
},
(error) => {
console.log(error);
},
function() {
uploadImage.snapshot.ref.getDownloadURL().then(function(downloadURL) {
firebase.firestore().collection('stack_overflow').add({
question_title: question_title,
question_image: question_image,
question_image_url: downloadURL
})
.then((res) => {
let id = res.id; //receive id of doc added
firebase.firestore().collection('stack_overflow').doc(id).set({question_id:id},{merge:true})
})
});
推荐阅读
- python - 使用 anaconda 的 Python 网络
- docker - Docker FastAPI 负载均衡与 NGINX
- python - 使用python在网站内查找广播流
- node.js - 有没有办法通过使用 Node.js 从 Sheets API 获得的规范来可视化图表?
- python - 网页抓取 ASP.NET 站点时,同一会话中的多个发布请求不起作用
- substrate - 削减验证者的 DOT 股份
- html - 如何制作溢出:动态高度滚动
- java - io.cucumber.core.exception.CucumberException:无法实例化类
- performance - DaCe 构建文件
- python - 如何阅读包含 numpy 的代码行?