0

I want to save images in Firebase Storage with its own name.....

so, this is my uploading code..

     storage.ref('users/'+ imgId + "/post.jpg").put(file).then(function () {
      console.log("uploaded");

and this is my retrieval code..

 storage.ref('users/'+ user.uid + "/post.jpg").getDownloadURL().then(img => {
            postImage = img
      }).catch(error => {
        console.log(error);
      })

Whats happening is that when ever I upload a new image it overrides the older image and also overrides the image in UI. can anyone has a solution ?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

0

By using storage.ref('users/'+ user.uid + "/post.jpg").put(file) you are uploading the file as users/USER_ID/post.jpg.

If the intention is to upload a "primary" image for a particular post, instead save the image as posts/POST_ID/main.jpg (hard to trace author) or users/USER_ID/images/POST_ID-main.jpg (easy to trace author).

// for "users/USER_ID/images/POST_ID-main.jpg"
const postImageRef = storage
  .ref('users/'+ user.uid + "/images/" + postId + "-main.jpg");
// OR
// for "users/USER_ID/images/POST_ID-main.jpg"
const postImageRef = storage
  .ref('users/'+ user.uid)
  .child("images")
  .child(postId + "-main.jpg");
// OR

// for "posts/POST_ID/main.jpg"
const postImageRef = storage
  .ref('posts/'+ postId)
  .child(main.jpg");
postImageRef.put(file)
  .then(() => {
    console.log("uploaded");
    return postImageRef.getDownloadURL();
  })
  .then((imageURL) => {
    // TODO: use imageURL
  })

As you seem to be setting a variable postImage from inside the promise, you are going to run into race conditions. To avoid that, switch to async/await syntax like so:

// elsewhere
const POSTS_REF = database.ref('posts');

const newPostRef = POSTS_REF.push();
const postId = newPostRef.key;
const postImageStorageRef = storage
  .ref('users/'+ user.uid)
  .child("images")
  .child(postId + "-main.jpg");

await postImageStorageRef.put(file);
console.log("uploaded");
const postImage = await postImageStorageRef.getDownloadURL();

// do something with postImage
await newPostRef
  .set({
    image: postImage,
    uid: user.uid,
    ...
  });
console.log("Created post #" + postId);
samthecodingman
  • 23,122
  • 4
  • 30
  • 54