我希望在提交表單時,選擇的文本輸入和文件應分別上傳到 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
用戶選擇的輸入。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句