【问题标题】:Uploading base64 to the firebase storage and getting back the download url将 base64 上传到 firebase 存储并取回下载 url
【发布时间】:2021-12-27 04:25:21
【问题描述】:

调用的第一个函数是addPostHandler,它调用函数storeImage。在 storeImage 函数内部, postData.postImage 是字符串数组(图像转换为 base64)。我在这里要做的是映射 postData.postImage 中的所有图像,然后将其上传到 firestore,然后获取下载 Url 并将其推送到 imageUrl。在我完成上传所有图像并获取 URL 后,最后我希望 console.log("Printing....") 运行。

错误是 storeImage 函数返回的是空字符串而不是 downloadUrl。

const index = () => {
  const storeImage = async (postData: PostType) => {
    const imageUrl: string[] = [];
    const storage = getStorage();
    postData.postImage.map((image, i) => {
      const storageRef = ref(
        storage,
        `ImagesOfPosts/${postData.userId}/${postData.postId}/image ${i}`
      );
      uploadString(storageRef, image, "data_url", {
        contentType: "image/jpg",
      }).then(() => {
        getDownloadURL(storageRef)
          .then((result) => {
            imageUrl.push(result);
          })
          .catch((error) => {
            console.error(error);
          });
      });
    });

    console.log(imageUrl);

    return imageUrl;
  };

  const addPostHandler = async (enteredPostData: PostType) => {
    const imageUrl = await storeImage(enteredPostData);
    console.log("Printing......."); 
}

【问题讨论】:

    标签: javascript reactjs typescript firebase firebase-storage


    【解决方案1】:

    您的顶级代码不会等到上传和获取下载 URL 完成,因此您会看到它返回一个空数组。

    由于您要上传多张图片,因此您需要使用Promise.all() 来仅在所有图片完成后解析storeImage

    总共会是这样的:

    const storeImage = async (postData: PostType) => {
      const storage = getStorage();
      const imageUrl = Promise.all(postData.postImage.map((image, i) => {
        const storageRef = ref(
          storage,
          `ImagesOfPosts/${postData.userId}/${postData.postId}/image ${i}`
        );
        return uploadString(storageRef, image, "data_url", {
          contentType: "image/jpg",
        }).then(() => {
          return getDownloadURL(storageRef);
        });
      });
    
      return imageUrl;
    };
    

    【讨论】:

      猜你喜欢
      • 2018-01-24
      • 2020-05-24
      • 2017-12-03
      • 2019-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-20
      • 1970-01-01
      相关资源
      最近更新 更多