Firebase图片URL上传数据库出错,如何获取有效存储链接?
问题修复方案
错误原因
你在成功获取Firebase Storage的下载链接后,没有使用这个有效链接,反而继续传入了本地的imageUri,导致数据库存储的是本地文件Uri而非云端存储链接。
修复代码
修改uploadToFireBase方法中创建HackathonModel的代码,将imageUri.toString()替换为回调返回的Firebase Storage下载链接,同时修正进度条的显示状态:
private fun uploadToFireBase(imageUri: Uri) { binding.progressBar.visibility = View.VISIBLE val fileRef : StorageReference = storageReference.child("${System.currentTimeMillis()}.${getFileExtension(imageUri)}") fileRef.putFile(imageUri).addOnSuccessListener { fileRef.downloadUrl.addOnSuccessListener { downloadUrl -> // 成功获取下载链接后隐藏进度条 binding.progressBar.visibility = View.INVISIBLE val hackathonModel = HackathonModel( binding.HackTitleET.text.toString(), binding.HackUrlET.text.toString(), binding.HackLocationET.text.toString(), downloadUrl.toString() // 这里使用Firebase Storage的云端下载链接 ) val hackathonModelId : String? = root.push().key root.child("HackathonsUsers").child(firebaseAuth.currentUser!!.uid).child(hackathonModelId.toString()).setValue(hackathonModel) root.child("AllHackathons").child(hackathonModelId.toString()).setValue(hackathonModel) Toast.makeText(this, "Hackathon Uploaded Successfully", Toast.LENGTH_SHORT).show() val intent = Intent(this , MainActivity::class.java) startActivity(intent) finish() } }.addOnProgressListener { binding.progressBar.visibility = View.VISIBLE }.addOnFailureListener{ binding.progressBar.visibility = View.INVISIBLE binding.postHackBT.visibility= View.VISIBLE Toast.makeText(this, "Uploading Failed", Toast.LENGTH_SHORT).show() } }
关键说明
fileRef.downloadUrl.addOnSuccessListener回调中的downloadUrl是Firebase Storage返回的公开可访问的云端文件链接,必须用这个值替换本地Uri存入数据库。- 修正了进度条逻辑:成功获取下载链接后应该隐藏进度条,之前的代码错误地保持了可见状态。
内容的提问来源于stack exchange,提问作者Yash_ Bhardwaj
相关产品推荐
相关产品推荐

