如何将多个图像上传到Firebase存储并返回多个下载URL [英] How to upload multiple images to Firebase Storage and return multiple downloadURLs

查看:73
本文介绍了如何将多个图像上传到Firebase存储并返回多个下载URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在开发一个简单的电子商务应用程序,需要上传多个产品图片.使用Vuejs和Vue-Croppa,我们需要将图像上传到Firebase存储,检索下载URL,然后在将产品添加到数据库时将这些URL包含在数组中.

We are working on a simple e-commerce app where we need to upload multiple product images. Using Vuejs and Vue-Croppa, we need to upload the images to firebase storage, retrieve the download URLs, then include those URLs in an array when we add that product to our database.

<croppa v-for="(c, i) in croppas"
  :key="i"
  v-model="croppas[i]"
  :width="150"
  :height="150"
  @new-image="croppas.push({})"
  v-show="i === croppas.length - 1 || c.imageSet"
></croppa>

以及我们的方法:

addProduct() {
    this.showSuccess = true
    let {details} = this
    this.croppas.forEach(file => {
        file.generateBlob(
            blob => {
                let rand = (Math.random().toString(36).substring(2, 16) + Math.random().toString(36).substring(2, 16)).toUpperCase()
                let imagesRef = storageRef.child('productimages/' + rand)
                let downloadURL
            imagesRef.put(blob).then((snap) => {
            imagesRef.getDownloadURL().then(function(downloadURL) {
              console.log('File available at', downloadURL)
            })
          })
      },
        'image/jpeg',
        0.8
        )
    })

    let shop = this.userStore.id
    let {details} = this
    console.log(shop)
    let createdAt = new Date().toString()
    let createdBy = this.currentUser.uid
    console.log(createdBy)
    let productImageUrl = downloadURL

    fb.productsCollection.add({ details, createdAt, createdBy, shop})
    .then( doc => {
      fb.productsCollection.doc(doc.id).update({
        id: doc.id, 
      })
   })
   .then( doc => {
      fb.productsCollection.doc(doc.id).update({
        productImages: productImageUrl
      })
   })

   setTimeout(() => {
    this.showSuccess = false
   }, 4000)
},

现在,我们收到控制台错误:

Right now, we are getting a console error:

Firebase Storage: Invalid argument in 'put' at index 0: Expected Blob or File.

此外,productImageUrl = downloadURL仅适用于一个文件,其中可能会有更多文件.我如何使它与数组一起工作?

Also, the productImageUrl = downloadURL would only work for one file, where there will be potentially more. How can me make this work with an array?

推荐答案

第二个问题.....

For your second issue.....

为您要上传的每张图片设置一个承诺.

Set up a promise for each image you want to upload.

因此,在您的循环中调用与以下方法相似"的方法(我刚刚从我的一个项目中将其抓取):

So in your loop call a method "similar" to the below (I've just grabbed this out of one of my projects):

uploadImageAsPromise (imageFile) {
    const self = this;

        return new Promise(function (resolve, reject) {
            var storageRef = firebase.storage().ref("/imagestestnew/"+imageFile.name);

            //Upload file
            var task = storageRef.put(imageFile);


            //Update progress bar
            task.on('state_changed',
                function progress(snapshot){

                    var percentage = snapshot.bytesTransferred / snapshot.totalBytes * 100;
                    console.log("percentage" + percentage)
                    self.progressUpload = percentage;
                },
                function error(err){
                    console.log("error")
                },
                function complete(){
                    console.log("done")
                    var downloadURL = task.snapshot.downloadURL;
                }
            );
        });
}

这篇关于如何将多个图像上传到Firebase存储并返回多个下载URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆