Creating a new unique path to Firebase Storage, co

2020-02-16 04:19发布

问题:

I have a marketplace web app, where users can upload items, and of course they can also see images associated with these items. The problem is organizing the storage buckets, I was thinking to make the path itemImages/itemUID/image1.jpg. The problem is getting the itemUID, which is automatically generated, after an item is added to the database.

Here's a code snippet I have for adding items to the db:

    itemsRef.push({
        title: title,
        description: description,
        tags: tags,
        price: price,
    });

and here's a simplified function I use to store an image:

var uploadTask = imageNewItemRef.child('fakeUID' + '/' +  imageNames[x]).putString(images[x], 'base64');

uploadTask.on('state_changed', function(snapshot) {

}, function(error) {
    console.log("error uploading image");
}, function() {
    var downloadURL = uploadTask.snapshot.downloadURL;
    console.log(downloadURL);
});

as you can see, I'm using a hardcoded fakeUID link for testing purposes, but I have no clue (and searching hasn't helped), on how to have a uniqueUID instead of a fake one, that is linked to the item :/

Any help is appreciated!

回答1:

Apologies for poorly written (and untested) JS, but would something like this work?

// create a new push ID and update the DB with some information
var currentItemRef = itemsRef.push({
    title: title,
    description: description,
    tags: tags,
    price: price,
}).then(function() {
  var storageRef = firebase.storage().ref();
  // currentItemRef.name is the unique key from the DB
  return storageRef.child(currentItemRef.name + '/' + imageNames[x]).putString(images[x], 'base64');
}).then(function(snapshot) {
  // update the DB with the download URL
  return currentItemRef.update({
    url: snapshot.metadata.downloadURLs[0]
  });
}).catch(function(error) {
  console.error(error);
});