【问题标题】:How to save images to Firebase Storage with their own name (HTML)?如何使用自己的名称(HTML)将图像保存到 Firebase 存储?
【发布时间】:2021-08-12 09:43:02
【问题描述】:

我想用自己的名字将图像保存在 Firebase 存储中.....

所以,这是我的上传代码..

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

这是我的检索代码..

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

发生的情况是,当我上传新图像时,它会覆盖旧图像并覆盖 UI 中的图像。谁能有解决方案?

【问题讨论】:

    标签: javascript html firebase firebase-storage


    【解决方案1】:

    通过使用storage.ref('users/'+ user.uid + "/post.jpg").put(file),您将文件上传为users/USER_ID/post.jpg

    如果打算为特定帖子上传“主要”图片,请将图片另存为posts/POST_ID/main.jpg(难以追踪作者)或users/USER_ID/images/POST_ID-main.jpg(易于追踪作者)。

    // 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
      })
    

    由于您似乎在 Promise 中设置了变量 postImage,因此您将运行 into race conditions。为避免这种情况,请切换到 async/await 语法,如下所示:

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

    【讨论】:

      猜你喜欢
      • 2021-03-14
      • 1970-01-01
      • 2020-12-18
      • 1970-01-01
      • 1970-01-01
      • 2016-09-18
      • 1970-01-01
      • 2017-08-10
      • 1970-01-01
      相关资源
      最近更新 更多