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);