从Firebase存储下载JSON文件 [英] Download json file from firebase storage
问题描述
让我重申一下我的问题.我有一个vue.js应用,可将json文件上传到Firebase存储区中的存储桶.我需要下载要在我的应用中使用的文件,但是当我尝试从Firebase存储下载json文件时,系统显示未捕获(承诺)未定义".错误.
Let me restate my question. I have a vue.js app that uploads a json file to a bucket in my firebase storage. I need to download the file to use in my app but when I try to download a json file from firebase storage I get a "Uncaught (in promise) undefined" error.
我想做的就是将文件下载回一个对象,以便在我的应用中使用
What I would like to do is download the file back into an object to use in my app
这是我下载和读取文件的代码:
Here is my code to download and read the file:
const storage = firebase.storage()
const storageRef = storage.ref()
const objectRef = storageRef.child('BUCKET/FILE_NAME.json')
objectRef.download(function (err, contents) {
if (!err) {
var jsObject = JSON.parse(contents.toString('utf8'))
console.log('jsObject ', jsObject)
}
})
更新:这是我的全部代码.我检查数据库是否有正在学习的课程.如果找到了,我想从存储中获取该课程,并从其内容中构建对象.
UPDATE: Here is my entire code. I check the DB for an active course. If found, I want to grab that course from storage and built out my object from its contents.
getActiveCourse({ dispatch }, { cid, user }) {
return new Promise((res, rej) => {
let userActiveCourse = []
let archivedUserCourses = []
let currentCourseRef = db.collection('currentcourses')
currentCourseRef = currentCourseRef.where('cid', '==', cid)
currentCourseRef = currentCourseRef.where('user', '==', user.uid)
currentCourseRef.get().then(snapshot => {
if (!snapshot.empty) {
snapshot.forEach(doc => {
let course = doc.data()
course.id = doc.id
if (course.status == 'active') {
// WE FOUND AN ACTIVE COURSE. NOW LETS DOWNLOAD IT AND READ IT INTO AN ARRAY
const storage = firebase.storage()
const storageRef = storage.ref()
const objectRef = storageRef.child('BUCKET/FILE_NAME.json')
objectRef.download(function (err, contents) {
if (!err) {
var jsObject = JSON.parse(contents.toString('utf8'))
}
})
userActiveCourse.push(course.course)
} else {
archivedUserCourses.push(course.course)
}
})
}
}).then(() => {
dispatch('addUserActiveCourse', userActiveCourse)
dispatch('addArchivedUserCourses', archivedUserCourses)
res()
}).catch(() => rej())
})
},
推荐答案
以下是任何需要此类问题帮助的人的解决方案.
Here was the solution for anyone else needing help with this type of issue.
const storage = firebase.storage()
const storageRef = storage.ref()
const objectRef = storageRef.child(course.storageRef)
objectRef.getDownloadURL().then((url) => {
axios.get(url).then((response) => {
let activeCourse = response.data
userActiveCourse.push(activeCourse)
})
})
这篇关于从Firebase存储下载JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!