如何从Firebase Storage的state_changed事件中获取图片下载URL?
解决Firebase Storage无法获取downloadURL的问题
我之前也碰到过完全一样的问题!图片明明成功上传到Storage了,但就是拿不到downloadURL,看你的控制台快照也确实没有这个字段——这是因为Firebase Storage的API已经更新,snapshot.downloadURL这个属性已经被废弃,不再直接从上传快照中提供了。
问题根源
在较新的Firebase Storage SDK版本中,官方移除了snapshot.downloadURL同步属性,改用异步方法getDownloadURL()来获取文件的下载链接,这个方法返回一个Promise,需要我们通过异步方式处理结果。
修改你的代码
你只需要把上传完成回调里获取下载链接的部分,替换成调用getDownloadURL()的逻辑就行,具体修改如下:
// upload file uploadFile(file, metadata) { if(file === null) return false let pathToUpload = this.currentChannel.id // parent means Messages.vue getMessagesRef() that returns either public or private channel let ref = this.$parent.getMessagesRef() // getPath() refers to the path below let filePath = this.getPath() + '/' + uuidV4() + '.jpg' // upload file this.uploadTask = this.storageRef.child(filePath).put(file, metadata) // upload state this.uploadState = "uploading" // on upload state change this.uploadTask.on('state_changed', snapshot => { console.log('image uploaded/state_changed in storage: ', snapshot) // Upload en cours let percent = (snapshot.bytesTransferred / snapshot.totalBytes) * 100 // $("#uploadedFile").progress("set percent", percent) $("progress-bar").css("width", percent+'%') }, error => { // Error this.errors.push(error.message) this.uploadState = 'error' this.uploadTask = null }, () => { // Upload finished this.uploadState = 'done' console.log('done upload') // reset form this.$refs.file_modal.resetForm() // 👇 核心修改:调用getDownloadURL()异步获取下载链接 this.uploadTask.snapshot.ref.getDownloadURL() .then(downloadURL => { console.log('获取到的下载链接:', downloadURL) // 拿到链接后发送消息 this.sendFileMessage(downloadURL, ref, pathToUpload) }) .catch(error => { console.error('获取下载链接失败:', error) this.errors.push(error.message) this.uploadState = 'error' }) }) },
额外优化(可选)
如果你习惯用async/await写法,也可以把完成回调改成异步函数,代码会更简洁:
// 将完成回调改为async函数 async () => { this.uploadState = 'done' console.log('done upload') this.$refs.file_modal.resetForm() try { const downloadURL = await this.uploadTask.snapshot.ref.getDownloadURL() console.log('获取到的下载链接:', downloadURL) this.sendFileMessage(downloadURL, ref, pathToUpload) } catch (error) { console.error('获取下载链接失败:', error) this.errors.push(error.message) this.uploadState = 'error' } }
这样修改后,你就能正常获取到文件的下载链接啦!
内容的提问来源于stack exchange,提问作者Ryan Dhungel
相关产品推荐
相关产品推荐

