我正在做一个项目,我通过来自不同用户的表单获取输入(文本和文件)并将其存储在云 Firestore 上。我已经成功地将来自不同用户的图像存储在 firebase 存储上,但现在我需要检索对应于不同用户的图像 url 并将其放在 firestore 数据库中。我可以在控制台上记录 url,但是当我尝试将它们添加到数据库时出现错误。我正在使用以下代码:
state ={
selectedFile1:null,
}
fileSelectedHandler1 = e =>{
this.setState({
selectedFile1: e.target.files[0]
})
fileUploadHandler1=()=>{
const storageRef = storage.ref('images/');
const fileRef = storageRef.child(this.state.selectedFile1.name)
var uploadTask=fileRef.put(this.state.selectedFile1)
uploadTask.on('state_changed', function(snapshot){
// Observe state change events such as progress, pause, and resume
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
switch (snapshot.state) {
case firebase.storage.TaskState.PAUSED: // or 'paused'
console.log('Upload is paused');
break;
case firebase.storage.TaskState.RUNNING: // or 'running'
console.log('Upload is running');
break;
}
}, function(error) {
console.log(error);
}, function() {
// Handle successful uploads on complete
// For instance, get the download URL: https://firebasestorage.googleapis.com/...
uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
console.log('File available at', downloadURL);
this.setState({downloadURL})
});
});
}
<Input type="file" name="image1" id="image2" onChange={this.fileSelectedHandler1}/>
<button onClick={this.fileUploadHandler1}>Upload</button>
//uploading data to firestore through onSubmit form
addProd = e => {
e.preventDefault();
const db = firebase.firestore();
const userRef = db.collection("Users").add({
prodname: this.state.prodname,
prodprice: this.state.prodprice,
prodcat: this.state.selectedView,
prodsize: this.state.prodsize,
proddetails: this.state.proddetails,
prodsubcat: this.state.prodsubcat,
prodimgurl: this.state.downloadURL
});
this.setState({
prodname:'',
prodprice:'',
prodsize:'',
proddetails:'',
prodsubcat:'',
selectedView:'Men',
});
};