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

Firebase Storage上传图片成功但无法获取DownloadUrl,报404错误求助

问题分析与解决方案

核心错误

你代码里上传文件的路径和获取下载URL的路径完全不一致:

  • 上传时用的是 storageReference.child("${calendar.timeInMillis}"),文件实际存在Profile_Pic/{时间戳}路径下
  • 但获取URL时却去storageReference.child(FirebaseAuth.getInstance().uid!!)查找,也就是Profile_Pic/{用户UID},这个路径下没有对应文件,所以触发404错误。

另外原代码的异步回调写法和suspend函数不兼容:回调还没执行完成,函数就已经返回初始值null的imageUri,这也会导致获取URL失败。

修复后的代码

使用Firebase Storage的KTX协程扩展处理异步操作,同时保证上传和获取URL的路径一致:

private val firebaseStorage: FirebaseStorage = FirebaseStorage.getInstance()
private val storageReference: StorageReference = firebaseStorage.getReference("Profile_Pic")

override suspend fun saveImageToFirebase(uri: Uri): String? {
    return try {
        // 生成唯一文件名(这里保留原逻辑用时间戳,也可替换为用户UID)
        val fileName = calendar.timeInMillis.toString()
        val fileRef = storageReference.child(fileName)
        
        // 等待上传完成
        fileRef.putFile(uri).await()
        
        // 获取并返回下载URL
        fileRef.downloadUrl.await().toString()
    } catch (e: Exception) {
        e.printStackTrace()
        Log.d("debug", "uploadImage: ${e.message}")
        null
    }
}

额外说明

  1. 需确保添加Firebase Storage的KTX依赖,否则await()方法无法使用:
    implementation 'com.google.firebase:firebase-storage-ktx:20.3.0' // 版本号以官方最新为准
    
  2. 如果你的需求是将文件存在Profile_Pic/{用户UID}路径下,只需把上传时的fileName替换为FirebaseAuth.getInstance().uid!!即可,保证前后路径统一。

内容的提问来源于stack exchange,提问作者Harpreet Singh.8052

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 12:03:20