【发布时间】:2022-01-04 15:16:19
【问题描述】:
我希望在提交表单时,文本输入和选择的文件应分别上传到 firestore 集合和 firebase 存储。我不明白为什么它会给我错误。
这是我的表格:
<form onSubmit={postSubmitHandler}>
<input type="text" ref={postTextRef}/>
<input type="file"/>
<button type="submit">Upload</button>
</form>
这是我的处理函数:
function postSubmitHandler(e) {
e.preventDefault();
const file = e.target .files[0];
console.log(file)
if (!file) return;
const sotrageRef = ref(storage, `posts/${file.name}`);
const uploadTask = uploadBytesResumable(sotrageRef, file);
uploadTask.on(
"state_changed",
(snapshot) => {
const prog = Math.round(
(snapshot.bytesTransferred / snapshot.totalBytes) * 100
);
setProgress(prog);
},
(error) => console.log(error),
() => {
getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
console.log("File available at", downloadURL);
firestore.collection('posts').doc(currentUser.uid).set({
imageURL: downloadURL,
caption: postTextRef.current.value,
postedAt: new Date(),
likes: 0
})
});
}
);
}
我得到的错误是:
TypeError: Cannot read properties of undefined (reading '0')
47 |
48 | function postSubmitHandler(e) {
49 | e.preventDefault();
> 50 | const file = e.target.files[0];
51 | ^
请帮助我更正此错误,或者如果有其他好的方法,请告诉我。
【问题讨论】:
标签: reactjs firebase google-cloud-firestore firebase-storage