You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase Storage上传报错storage/retry-limit-exceeded的解决求助

Firebase Storage uploadBytes上传进度卡0%并触发retry-limit-exceeded错误的解决办法

问题描述

提交表单时,uploadBytes()执行后上传进度卡在0%,随后触发报错:
FirebaseError: Firebase Storage: Max retry time for operation exceeded, please try again. (storage/retry-limit-exceeded)

已添加文件大小限制,更换正常运行的Firebase Storage项目测试后,问题仍复现。

排查与解决步骤

1. 添加错误捕获,定位具体问题

当前代码未对uploadBytes添加错误捕获,无法获取更详细的错误信息。修改代码添加try-catch:

const onSubmit = async (data: FieldValues) => {
    const { currIngridientName, ...restData } = data;
    const id = v4();

    if(data.imageFile[0] && data.imageFile[0].size < 71680) {
        setIsImageUploading(true);
        const storageRef = ref(storage, `folder/${data.imageFile[0].name}`);
        
        try {
            const res = await uploadBytes(storageRef, data.imageFile[0]);
            setIsImageUploading(false);
            console.log('上传成功', res);
        } catch (error) {
            setIsImageUploading(false);
            console.error('上传失败详情:', error);
        }
    } else {
        alert('file is too big');
    }
}

通过控制台打印的错误详情,可快速定位是权限、网络还是文件本身的问题。

2. 改用uploadBytesResumable监听进度与错误

uploadBytes无进度反馈,改用uploadBytesResumable可实时查看上传状态,同时更精准处理错误类型:

const onSubmit = async (data: FieldValues) => {
    const { currIngridientName, ...restData } = data;
    const id = v4();

    if(data.imageFile[0] && data.imageFile[0].size < 71680) {
        setIsImageUploading(true);
        // 用uuid+文件名避免重复覆盖
        const storageRef = ref(storage, `folder/${id}-${data.imageFile[0].name}`);
        const uploadTask = uploadBytesResumable(storageRef, data.imageFile[0]);

        uploadTask.on('state_changed', 
            (snapshot) => {
                const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
                console.log(`上传进度: ${progress}%`);
            }, 
            (error) => {
                setIsImageUploading(false);
                console.error('上传错误:', error);
                // 根据错误码针对性处理
                switch (error.code) {
                    case 'storage/unauthorized':
                        alert('无上传权限,请检查Storage规则');
                        break;
                    case 'storage/unknown':
                        alert('网络异常,请检查连接');
                        break;
                }
            }, 
            () => {
                setIsImageUploading(false);
                getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
                    console.log('文件访问地址:', downloadURL);
                    // 后续可将URL存入数据库
                });
            }
        );
    } else {
        alert('file is too big');
    }
}

3. 检查Firebase Storage规则

确保Storage规则允许当前用户上传文件,测试阶段可临时放开规则(生产环境需严格限制):

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /folder/{allPaths=**} {
      allow read, write: if true; // 测试用,生产环境替换为认证用户校验
    }
  }
}

4. 验证Firebase配置正确性

确认@/firebase/config中的配置信息完整且正确,且环境变量以NEXT_PUBLIC_开头(客户端组件需读取公开变量):

import { initializeApp } from "firebase/app";
import { getStorage } from "firebase/storage";

const firebaseConfig = {
  apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
  authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
  storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID
};

const app = initializeApp(firebaseConfig);
export const storage = getStorage(app);

5. 确认文件可正常读取

添加文件预览逻辑,验证选中的文件可被正常读取,排除文件损坏或读取异常问题:

<input 
  type="file" 
  id='imgUpload' 
  {...register('imageFile', { required: 'Завантажте картинку!' })} 
  className='opacity-0 invisible w-0 h-0 absolute -z-10'
  onChange={(e) => {
    if (e.target.files && e.target.files[0]) {
      const file = e.target.files[0];
      const reader = new FileReader();
      reader.onload = (event) => {
        setCurrSelectedImgSrc(event.target?.result as string);
      };
      reader.readAsDataURL(file);
    }
  }}
/>

内容的提问来源于stack exchange,提问作者Andremaxico

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 21:45:13