Firebase Storage上传图片后获取Download URL报错求助
问题分析
你遇到的TypeError: ref._throwIfRoot is not a function错误,核心原因是**getDownloadURL()需要传入Firebase Storage的引用对象,而非字符串路径**。另外代码里还有两处关键错误:
- 错误拼接Storage引用与字符串:
const filePath =${productImagesRef}/${fileName};中,productImagesRef是Storage引用对象,直接和字符串拼接会生成无效路径(格式为[object Object]/xxx),导致后续创建的imageRef不符合预期。 - 传递路径字符串给
getDownloadURL:你在then(path => getDownloadURL(path))里把字符串路径传给了getDownloadURL,但该方法要求传入的是通过ref()或child()创建的Storage引用实例。
修正方案
方案1:利用上传后的快照引用直接获取下载URL(推荐)
上传完成后,snapshot.ref就是当前文件的Storage引用,直接用它调用getDownloadURL即可,无需再处理路径:
const productImagesRef = ref(storage, 'images/product-images'); function getImageURL(fileName, file) { // 用child方法创建子引用,避免拼接错误 const imageRef = productImagesRef.child(fileName); return uploadBytes(imageRef, file) .then(snapshot => { console.log(`File: ${fileName} uploaded successfully.`); // 直接使用快照的ref获取下载URL return getDownloadURL(snapshot.ref); }) .then(src => { console.log(src); return src; }) .catch(e => { console.error(e); }) }
方案2:通过路径重新创建引用后获取URL
如果一定要用路径,需要先通过ref(storage, path)重新创建合法的Storage引用:
function getImageURL(fileName, file) { // 直接用字符串路径创建引用,避免拼接对象 const filePath = `images/product-images/${fileName}`; const imageRef = ref(storage, filePath); return uploadBytes(imageRef, file) .then(snapshot => { console.log(`File: ${fileName} uploaded successfully.`); return snapshot.metadata.fullPath; }) .then(path => { console.log(typeof path, path); // 先创建引用再传进去 const fileRef = ref(storage, path); return getDownloadURL(fileRef); }) .then(src => { console.log(src); return src; }) .catch(e => { console.error(e); }) }
额外修复:表单提交中的状态异步问题
handleSubmit里setImageSrc(src)是异步操作,直接紧接着用imageSrc可能拿不到最新值,建议直接使用返回的src:
async function handleSubmit() { let src = await getImageURL(imageName, imageFile); // 直接使用src,不用等setImageSrc更新状态 const data = { id: id, imageSrc: src, // 这里改用src description: description, category: category, discount: discount, discountPrice: discountPrice, price: price, sizes: sizes, totalQuantity: quantity, type: type, } console.log(data); if(src) await addProducts(data); // 这里也改用src判断 // 重置状态代码不变... alert('Added'); }
内容的提问来源于stack exchange,提问作者MACXDON
相关产品推荐
相关产品推荐

