将图像上传到 firebase 存储并同时将文本输入到 firestore 时出错
Error while uploading image to firebase storage and text input to firestore simultaneously
我希望在提交表单时,选择的文本输入和文件应分别上传到 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 | ^
请帮我更正这个错误,或者如果有其他好的方法请告诉我。
由于您的 postSubmitHandler
正在响应正在提交的 form
,它的 e.target
指向表单元素 - 而不是文件所在的 input
。
快速修复:
const input = e.target.querySelector("input[type='file']");
const file = input.files[0];
此处的第一行从您的表单 (e.target
) 中选择正确的输入,然后用于访问用户选择的 files
。
我希望在提交表单时,选择的文本输入和文件应分别上传到 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 | ^
请帮我更正这个错误,或者如果有其他好的方法请告诉我。
由于您的 postSubmitHandler
正在响应正在提交的 form
,它的 e.target
指向表单元素 - 而不是文件所在的 input
。
快速修复:
const input = e.target.querySelector("input[type='file']");
const file = input.files[0];
此处的第一行从您的表单 (e.target
) 中选择正确的输入,然后用于访问用户选择的 files
。