React结合Firebase/Firestore v9向已有文档传图失败求助
Firebase Storage 上传文件失败排查(404错误)
问题场景
使用最新版Firebase + NextJS + React开发,尝试通过uploadString和uploadBytesResumable方法上传图片到Firebase Storage,始终失败。Firestore规则已设置为允许全读写:
- 仅提交文本时,能正常写入Firestore文档;
- 同时提交文本和文件时,只有文本成功上传,文件上传失败;
- 调试时确认
imgFile和filePickerRef.current.files[0]均能获取到正确的File对象,但上传报错。
错误信息
FirebaseError: Firebase Storage: An unknown error occurred, please check the error payload for server response. (storage/unknown)
服务器响应:
{ "error": { "code": 404, "message": "Not Found." } }
核心上传代码
const uploadMessage = (event) => { event.preventDefault() if (!inputRef.current.value) return addDoc(collection(db, 'msgs'), { message: inputRef.current.value, timestamp: serverTimestamp() }).then(docRef => { if (imgFile) { const file = imgFile // 注意:此处存在拼写错误 storafeRef → storageRef const storafeRef = ref(storage, `msgs/${docRef.id}`) const uploadTask = uploadBytesResumable(storafeRef, file) uploadTask.on("state_changed", snapshot => { const progress = Math.round((snapshot.bytesTransferred / snapshot.totalBytes) * 100) setProgresspercent(progress) }, error => { alert(error) }, () => { getDownloadURL(uploadTask.snapshot.ref).then(url => { setDoc(doc(db, 'msgs', docRef.id), { url }, { merge: true }) }) }) console.log('image uploaded.') } else { console.log('no image.') } console.log('Added doc: ', docRef.id) }).then(() => { inputRef.current.value = '' setImageToPost(null) setImgFile(null) filePickerRef.current.value = '' console.log('removed image.') }).catch(error => { console.error("Error adding document: ", error); }) }
当前Firestore规则
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read, write; } } }
排查与解决方案
修复变量拼写错误
代码中storafeRef存在笔误,正确应为storageRef。拼写错误会导致创建的Storage引用无效,直接触发404错误。检查Firebase Storage规则
注意:你提供的是Firestore规则,而非Firebase Storage规则。Storage默认禁止未认证用户上传,需单独配置:
临时测试可设置开放规则:rules_version = '2'; service firebase.storage { match /b/{bucket}/o { match /{allPaths=**} { allow read, write: if true; } } }正式环境建议根据用户认证状态限制权限。
确认Storage实例初始化正确
确保已正确初始化Storage实例:import { getStorage } from "firebase/storage"; const storage = getStorage(app); // app为已初始化的FirebaseApp实例优化异步流程
当前状态重置逻辑(清空输入、重置文件状态)会同步执行,可能提前销毁文件引用。建议将清理逻辑移到上传完成的回调内:() => { getDownloadURL(uploadTask.snapshot.ref).then(url => { setDoc(doc(db, 'msgs', docRef.id), { url }, { merge: true }) }).then(() => { // 上传完成后再清理状态 inputRef.current.value = '' setImageToPost(null) setImgFile(null) filePickerRef.current.value = '' console.log('removed image.') }) }
内容的提问来源于stack exchange,提问作者user20006944
相关产品推荐
相关产品推荐

