저는 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});
// **************************이 부분이 작동하지 않습니다 (START) ************** *******************
const [imgURL, setImgURL] = useState('')
firebase
.firestore()
.collection('notes')
.add({
imgURL
})
.then(() => {
setImgURL('')
})
// ******************************이 부분은 작동하지 않습니다. (END) ********** **********************
})
});
}
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('')
})
});
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다