Flutter Web用Supabase uploadBinary传文件遇413 Payload过大错误
Flutter Web上传Supabase存储桶遇413 Payload过大错误解决方法
问题描述
在Flutter Web中使用uploadBinary方法上传图片到Supabase存储桶时,无论文件大小(日志显示仅55KB),均触发以下错误:
StorageException(message: The object exceeded the maximum allowed size, statusCode: 413, error: Payload too large)
上传代码如下:
Future<void> uploadImages(List<XFile> images) async { state = UploadingPictures(); final client = ref.read(getSupabaseClientProvider); final storageClient = ref.read(getSupabaseStorageClientProvider); for (var image in images) { final extension = image.path.split('.').last; final name = image.path.split('/').last; final bytes = await image.readAsBytes(); LoggerUtil.d('bytes: ${bytes.length}', tag: '[UploadImagesViewModel].uploadImages'); storageClient .from(SupabaseStorageConstants.serviceFolder) .uploadBinary('$name.$extension', bytes) .then((value) { LoggerUtil.d('uploadImage: $value'); }).catchError((error) { LoggerUtil.e('uploadImage: $error'); state = ErrorUploadingPictures(error.toString()); }); } state = SuccessUploadingPictures(); }
原因分析
Supabase确实存在上传相关限制,小文件触发报错的核心原因通常是:
- Supabase Edge Functions默认请求体大小限制为1MB,即使存储桶允许更大文件,请求体超限也会先触发413错误
- 存储桶本身默认单个文件最大限制为6MB,但如果请求先被Edge Functions拦截,就会出现小文件也报错的情况
解决步骤
1. 调整存储桶文件大小限制
- 登录Supabase控制台,进入目标项目
- 切换到Storage页面,找到对应的存储桶
- 点击存储桶的Settings选项
- 在Max file size字段设置合适的最大值(如50MB),保存更改
2. 调整Edge Functions请求体限制(若适用)
如果上传请求经过Edge Functions处理,需修改函数配置:
- 打开项目的
supabase/functions目录,找到对应函数的package.json - 添加配置项,示例:
"config": { "memory": "1024MB", "maxPayloadSize": "50MB" } - 重新部署该Edge Functions
3. 代码优化
原代码存在异步操作未等待就设置成功状态的问题,同时可能生成重复扩展名的文件名,优化后代码:
Future<void> uploadImages(List<XFile> images) async { state = UploadingPictures(); final storageClient = ref.read(getSupabaseStorageClientProvider); bool uploadFailed = false; for (var image in images) { try { // 拆分出不带扩展名的文件名,避免重复添加 final pathSegments = image.path.split('/'); final fullFileName = pathSegments.last; final name = fullFileName.split('.').first; final extension = fullFileName.split('.').last; final bytes = await image.readAsBytes(); LoggerUtil.d('bytes: ${bytes.length}', tag: '[UploadImagesViewModel].uploadImages'); final uploadResult = await storageClient .from(SupabaseStorageConstants.serviceFolder) .uploadBinary('$name.$extension', bytes); LoggerUtil.d('uploadImage: $uploadResult'); } catch (error) { LoggerUtil.e('uploadImage: $error'); state = ErrorUploadingPictures(error.toString()); uploadFailed = true; break; // 出错后终止上传,可根据需求改为继续上传其余文件 } } if (!uploadFailed) { state = SuccessUploadingPictures(); } }
内容的提问来源于stack exchange,提问作者Dean
相关产品推荐
相关产品推荐

