如何以不同的方法在 firebase 中上传多个图像?

How can I upload multiple images in firebase at react in different method?

我想 console.log()console.log(list) 我的图像 uploadBytes 中,这样我就可以实现它并在我的后端传递它而不用分离它。

代码是这样的

const handleSubmitForm = e => {
    e.preventDefault()
    alert("Your Images Is Uploaded")

    const imagesRef = ref(storage,`GALLERY/${image.name}${v4()}`)
    const imagesRef2 = ref(storage,`GALLERY/${image2.name}${v4()}`)
    const imagesRef3 = ref(storage,`GALLERY/${image3.name}${v4()}`)
    const imagesRef4 = ref(storage,`GALLERY/${image4.name}${v4()}`)
    const imagesRef5 = ref(storage,`GALLERY/${image5.name}${v4()}`)
    const id = v4()
    const Uploads = async() => {
        const list = []
        uploadBytes(imagesRef,image)
        .then((snapshot) => {
          getDownloadURL(snapshot.ref).then((url) => {
            console.log('Image uploaded' + `${url}`)
            const item = url
            list.push(item)
          })
        })
        uploadBytes(imagesRef2,image2)
        .then((snapshot) => {
          getDownloadURL(snapshot.ref).then((url) => {
            console.log('Image uploaded' + `${url}`)
            const item = url
            list.push(item)
          })
        })
        uploadBytes(imagesRef3,image3)
        .then((snapshot) => {
          getDownloadURL(snapshot.ref).then((url) => {
            console.log('Image uploaded' + `${url}`)
            const item = url
            list.push(item)
          })
        })
        uploadBytes(imagesRef4,image4)
        .then((snapshot) => {
          getDownloadURL(snapshot.ref).then((url) => {
            console.log('Image uploaded' + `${url}`)
            const item = url
            list.push(item)
          })
        })
        uploadBytes(imagesRef5,image5)
        .then((snapshot) => {
          getDownloadURL(snapshot.ref).then((url) => {
            console.log('Image uploaded' + `${url}`)
            const item = url
            list.push(item)
          })
        })
        console.log(list)
    }
    Uploads()
}

我这里唯一的问题是 const list = [],其中我想在我的列表中追加每个 uploadBytes,这样我就不必重复调用后端,因为 Imma 放了一个后端每个 uploadBytes 都有,但我想让它更简单,只需将它推入列表即可。

我尝试异步执行,但没有成功。它只是给了我一个空数组,因为我不知道?我只是想我需要将 uploadBytes 设置为异步,但仍然不起作用。

如果我对你的问题的理解正确,你想在所有图片上传 URL 后记录下载列表。

这要求您为每次上传处理两个异步操作:

  • 数据本身的上传,
  • 获取下载的调用 URL。

由于您需要为每张图片执行此操作,因此您需要一个 Promise.all,并且由于它是两个调用,因此您需要一个链式 then 操作。

结合这导致:

// Helper function to upload an image and get back its download URL
const UploadSingleImage = (ref, image) => {
  return uploadBytes(ref, image).then((snapshot) => {
    return getDownloadURL(ref);
  })
}

const Uploads = async () => {
  const list = await Promise.all([
    UploadSingleImage(imagesRef,  image),
    UploadSingleImage(imagesRef2, image2),
    UploadSingleImage(imagesRef3, image3),
    UploadSingleImage(imagesRef4, image4),
    UploadSingleImage(imagesRef5, image5)
  ]);

  console.log(list)
}