firebase storage, retrieving an image to a vue app - javascript

I am trying to download an image from my firebase storage to render it in my Vue app, the upload from the application to the firebase storage is successful, however upon retrieval it gives me an error, i am using the firebase SDK in a Vue CLI 3 setup and vuex to manage my state. Here is the function setting in my actions in the main store.js file
createMeetUp({commit, getters}, payload) {
//here my payload is an object contains the following props
const meetup = {
title: payload.title,
location: payload.location,
date: payload.date.toISOString(),
description: payload.description,
creatorId: getters.user.id
}
let imageUrl
let key
//now i am reaching out to the firebase database to store the above object
firebase.database().ref('meetup').push(meetup)
.then(data => {
key = data.key
return key
})
.then(key => {
//also in my payload object i stored an image file
//so here i am uploading the image to the firebase storage
const fileName = payload.image.name
const extension = fileName.slice(fileName.lastIndexOf('.'))
return firebase.storage().ref('meetup/' + key + '.' + extension).put(payload.image)
})
.then(imageInfo => {
//the issue is here in this then() block as i am stuck on how to retrieve the image from the storage to render it in the app
imageUrl = imageInfo.getDownloadURL()
return firebase.database().ref('meetups').child(key).update({
imageUrl: imageUrl
})
})
.then(() => {
//here i am simply commiting my mutation..
commit('createMeetUp', {
...meetup,
imageUrl: imageUrl,
id : key
})
})
.catch(err => console.log(err))
}
the error I am getting is:
TypeError: imageInfo.getDownloadURL is not a function
Again I believe the issue is in the then() block where I retrieve the image from the firebase storage.
thanks in advance

Following the comments above, the following should work if I am not mistaking (not tested...).
Note that getDownloadURL() returns a promise (see here), therefore you have to chain the promises.
....
.then(key => {
//also in my payload object i stored an image file
//so here i am uploading the image to the firebase storage
const fileName = payload.image.name
const extension = fileName.slice(fileName.lastIndexOf('.'))
return firebase.storage().ref('meetup/' + key + '.' + extension).put(payload.image)
})
.then(uploadTaskSnapshot => {
return uploadTaskSnapshot.ref.getDownloadURL()
})
.then(imageUrl => {
return firebase.database().ref('meetups').child(key).update({
imageUrl: imageUrl
})
})
....

Related

Create an array whenever an image is uploaded using url and then store a object into that array in firestore

I am able to get url, caption and id of an image using an object and then store them into firestore field but the problem is, I need them to be stored into an array so I can retrieve and display the images onto my UI. Currently firestore field is returning an array
I tried to merge class object with an array, push the object into the array and using normal object instead of class object.
`
class App {
constructor() {
this.posts = [];
this.post = {
id: cuid(),
caption: "",
image: "",
};
getFileUrl(name) {
const imageRef = storage.ref(name);
imageRef
.getDownloadURL()
.then((url) => {
this.post.image = url;
console.log(this.post.image);
this.savePosts();
this.render();
})
.catch((error) => {
console.log(error, "Error Occured");
});
}
savePosts() {
db.collection("users")
.doc(this.userId)
.set({
post: this.posts,
})
.then(() => {
console.log("Document successfully written!");
})
.catch((error) => {
console.error("Error writing document: ", error);
});
}
render() {
this.savePosts();
}
`
firestore
If think you're looking for:
this.post.image.push(url);
If you tried that and ran intro problems, edit your question to show the exact code you tried and where you got stuck (including any error message or the erroneous result you got).

How do add value to a map, from a variable in firebase?

I am trying to add a map to a key in fire-store. Getting undefined in console and it is adding a empty map in firetsore.
I am uploading a multiple files at once in storage and getting imageUrls.
imageUrls={0:0.png,1:1.png} from this function.
const onUploadFiles = async (images) => {
let imageUrls = {};
Promise.all(
images.map(async (image) => {
const fileRef = storage.ref(`${scanID}/${chapterNumber}/${image.name}`);
await fileRef.put(image);
imageUrls[getFileName(image.name)] = await fileRef
.getDownloadURL()
.toString();
console.log(imageUrls[getFileName(image.name)]);
})
);
return imageUrls;
};
Once the files are uploaded I am trying to add this map to a document and adding it in firestore.
Utitlity function to store the name of the file as key.
const getFileName = (name) => name.replace(/\.[^/.]+$/, '');
Adding these url as a document.
//add chapter to firestore
const addChapter = async (images) => {
var chapter = {
id: uuidv4(),
title: title,
chapterNumber: chapterNumber,
};
await onUploadFiles(images)
.then((imageUrls) => {
chapter['images'] = imageUrls;
})
.catch((error) => {
console.log('Something went wring with database');
});
db.collection('chapters')
.doc(scanID)
.set(
{
[chapterNumber]: chapter,
},
//merge
{ merge: true }
)
.then(() => {
console.log('Done');
});
};
Expected output:
{
"0":{
"title":"title 1",
"id":"232131-321-312-331",
"chapterNumber":0,
"images":{
"0":"0.png",
"1":"1.png"
}
}
}
I am getting an empty map {} in firestore.
If I’m not misunderstanding, you would like to upload the images first to Firebase Cloud Storage buckets, and then retrieve the download URLs to include them in a document you are creating for a Firestore collection. If that’s the case, then in this related question there is a script that can help you upload images to Firebase Storage. I have tested this script, and it’s working on my test Node environment. Something I noticed from your code and the script I linked is that there is no firebaseStorageDownloadTokens property that provides a download token for your URLs:
const metadata = {
metadata: {
// This line is very important. It's to create a download token.
firebaseStorageDownloadTokens: uuid()
},
...
I have linked a guide related to downloading tokens and how to create them and obtain them. Finally, as to how to create Map objects from a variable to add to Firestore, the documentation provides an example of an object for Firestore:
const data = {
stringExample: 'Hello, World!',
booleanExample: true,
numberExample: 3.14159265,
dateExample: admin.firestore.Timestamp.fromDate(new Date('December 10, 1815')),
arrayExample: [5, true, 'hello'],
nullExample: null,
//Map object
objectExample: {
a: 5,
b: true
}
};

React Native Firebase: I'm trying to upload profile image via cloud storage but the function in 'then()' is not responding

I'm trying to upload profile picture and for this I'm using firebase cloud storage and firebase real-time database, i've to call another function in then() but it's not working for some reason. Please correct my mistake..
uploadImage = async uri => {
const response = await fetch(uri);
const blob = await response.blob();
var FilePath = imageId + '.' + this.state.currentFileType;
storage()
.ref('user/' + userid + './img')
.child(FilePath)
.put(blob)
.then(snap => {
snap.ref.getDownloadURL().then(downloadURL => {
console.log(downloadURL);
this.processUpload(downloadURL);
});
})
.catch(err => {
console.error(err);
});
};
With catch callback, I'm getting this
[TypeError: undefined is not an object (evaluating
'snap.ref.getDownloadURL')]

Cannot get Url from filebase storage?

I am trying to retrieve data url from firebase storage. I have a static function to get url, but the return is always undefined? How can I get the url of the file and store to my database?
uploadImageByDataURL(image, imageName, directory) {
const uploadTask = firebase.storage().ref(`images/${directory}/${imageName}`).putString(image, 'data_url');
uploadTask.on('state_changed', () => {
firebase.storage().ref(`images/${directory}`).child(`${imageName}`).getDownloadURL().then(url => {
return url
})
})
}
Retrieving the download URL happens asynchronously. Any code that requires the download URL, should be in the corresponding then() block. So:
const uploadTask = firebase.storage().ref(`images/${directory}/${imageName}`).putString(image, 'data_url');
uploadTask.on('state_changed', () => {
firebase.storage().ref(`images/${directory}`).child(`${imageName}`).getDownloadURL().then(url => {
firebase.database().reference().set(url);
})
})

Return data ID upon uploading Image in angular ts and firebase

Im uploading an image using angularTS and firebase. my plan is to upload an image and saved the following data. after that I expect a return ID from the firebase database callback. problem is, I can't get the data because it return to me like this.
__zone_symbol__state : true
__zone_symbol__value : "viHnY2OpUnJkO2VbfgwJ"
__proto__ : Object
this is my code for uploading image.
this.venueSvc.setVenuePhoto(this.venue, this.photo[0])
.subscribe(snapshot => {
console.log(snapshot);
console.log(snapshot.__zone_symbol__value);
console.log(snapshot.value);
});
and this is my service to upload the image to firebase database.
setVenuePhoto(venue: any, photo: File): Observable<any> {
console.log(venue);
let subjectTemp: any;
let uploadPhoto: any;
const uploadTask = firebase.storage()
.ref().child(this.PATH_VENUES + '/' + photo.name)
.put(photo);
uploadTask.on('state_changed', snapshot => {
uploadPhoto = snapshot;
let progress = Math.floor((uploadPhoto.bytesTransferred / uploadPhoto.totalBytes) * 100);
}, error => {
console.log(error);
}, () => {
venue.dateCreated = firebase.firestore.FieldValue.serverTimestamp();
venue.dateUpdated = firebase.firestore.FieldValue.serverTimestamp();
venue.venuePhoto = uploadPhoto.task.snapshot.downloadURL;
subjectTemp = this.venuesCollection.add(<Venue>venue.getData()).then(value => {
return value.id
});
this.viewUploadSubject.next(subjectTemp);
});
return this.viewUploadSubject;
}
I should be able to get the ID because im gonna need it to update the venue. Any suggestion would be appreciated.
You are uploading your image to Storage, not Firebase. They are two different services, and Storage doesn't provide and ID for file that you update.
If you want to reference an file from Storage, you can just save It's path.
Or you can save an reference for this file on Firebase so that you can get references from files more easily.
You could save the downloadUrl in the database instead of the id
uploadPhoto.task.snapshot.downloadURL
I don't know the structure of the rest of your app but you could save the downloadURL either update the db in your complete method on the upload
uploadTask.on('state_changed', progress, error, complete);
or save it the downloadUrl in state and after the upload save the url to the database

Categories

Resources