gpt4 book ai didi

reactjs - 如何在 React.js 中将图像上传到 Firebase 存储并同时将 URL 上传到 Firestore?

转载 作者:行者123 更新时间:2023-12-01 21:42:12 25 4
gpt4 key购买 nike

我是 React.js 的新手,我正在尝试将图像上传到 Firebase 存储,并且在成功上传后我试图同时将 downloadURL 推送到 Firestore。怎么做?这是上传图片正常但 firestore 不工作的代码。

    import React, {useState, Component} from 'react';
import firebase from "../firebase";

const storage = firebase.storage();

class ImageUpload extends Component {
constructor(props) {
super(props);
this.state = {
image: null,
url: '',
progress: 0
}
this.handleChange = this
.handleChange
.bind(this);
this.handleUpload = this.handleUpload.bind(this);
}
handleChange = e => {
if (e.target.files[0]) {
const image = e.target.files[0];
this.setState(() => ({image}));
}
}
handleUpload = () => {
const {image} = this.state;
const uploadTask = storage.ref(`images/${image.name}`).put(image);
uploadTask.on('state_changed',
(snapshot) => {
// progrss function ....
const progress = Math.round((snapshot.bytesTransferred / snapshot.totalBytes) * 100);
this.setState({progress});
},
(error) => {
// error function ....
console.log(error);
},
() => {
// complete function ....
storage.ref('images').child(image.name).getDownloadURL().then(url => {
console.log(url);
this.setState({url});

//*************************** 这部分不工作(开始)*********** **********************

                const [imgURL, setImgURL] = useState('')

firebase
.firestore()
.collection('notes')
.add({
imgURL
})
.then(() => {
setImgURL('')
})

//****************************** 这部分不工作(完) ******* *************************

            })
});
}
render() {

return (
<div>
<progress value={this.state.progress} max="100"/>
<br/>
<input type="file" onChange={this.handleChange}/>
<button onClick={this.handleUpload}>Upload</button>
<br/>

<img src={this.state.url || 'http://via.placeholder.com/400x300'} alt="Uploaded images" height="300" width="400"/>
</div>
)
}
}
export default ImageUpload;

最佳答案

要将下载URL写入数据库,你不需要将其存储在状态中。您可以直接在 then 处理程序中将其写入数据库:

storage.ref('images').child(image.name).getDownloadURL().then(url => {
firebase
.firestore()
.collection('notes')
.add({
imgURL: url
})
.then(() => {
setImgURL('')
})
});

关于reactjs - 如何在 React.js 中将图像上传到 Firebase 存储并同时将 URL 上传到 Firestore?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61215555/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com