问题
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())
})
},
回答1:
Steps to start a Firebase project
Open the Firebase console. Click “CREATE NEW PROJECT”.
- The “Create a project” window opens.
- The start screen of the Firebase console opens.
- The “Enter app details” screen opens.
- Continue the configuration by following the on-screen instruction.
- Check the server key after the project is created.
- Down the server key and store it on your local drive for now.
Now that we have installed dependencies and created a Firebase project, just create an index.js file and paste the below code. Don’t worry, we will go over the code in detail, to understand what is happening.
回答2:
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)
})
})
来源:https://stackoverflow.com/questions/66065378/download-json-file-from-firebase-storage