如何使用 Vue.js 将多个图像上传到 firebase v9 存储并获取所有下载 URL 以在云 firestore 数据库中更新它

Roh*_*ala 2 javascript google-cloud-storage firebase vue.js google-cloud-firestore

Vue 开发工具屏幕截图 控制台日志 屏幕截图

脚本代码:

 import firebase from "@/firebase";
    import {
      getStorage,
      ref,
      uploadBytes,
      getDownloadURL,
      updateDoc,
    } from "firebase/storage";
    export default {
      data() {
        return {
          imagesUrl: [],
        };
      },
      methods: {
        chooseFile() {
          document.getElementById("imgUpload").click();
        },
    
        uploadImage(e) {
          this.files.push(e.target.files[0]);
          this.images.push(URL.createObjetURL(this.files));
        },
        createCity: async function () {
          const docRef = firebase.addDoc(
            firebase.collection(firebase.firestoreDB, "cities"),
            {
              name: "Tokyo",
              country: "Japan",
            }
          );
    
          var photos = [];
    
          for (var i = 0; i < this.files.length; i++) {
            // files.values contains all the files objects
            const file = this.files[i];
            const storage = getStorage();
            const metadata = {
              contentType: "image/jpeg",
            };
            const storageRef = ref(storage, "temp/" + docRef.id + "/" + file.name);
    
            const snapshot = await uploadBytes(storageRef, file, metadata);
            const downloadURL = await getDownloadURL(snapshot.ref);
            photos.push(downloadURL);
          }
          await console.log(photos);
          await updateDoc(docRef.id, { photosURLs: photos });
        },
      },
    };
Run Code Online (Sandbox Code Playgroud)

控制台日志数据:

  • TypeError: Object(...) 不是 VueComponent._callee$ (fragment.vue?262c:453:1) at tryCatch (runtime.js?96cf:63:1) at Generator.invoke [as _invoke] ( runtime.js?96cf:294:1) 在 Generator.eval [作为下一个] (runtime.js?96cf:119:1) 在 asyncGeneratorStep (asyncToGenerator.js?1da1:3:1) 在 _next (asyncToGenerator.js?1da1) :25:1)

Ren*_*nec 5

您不应在循环中使用关键字await,请参阅此处此处forforEach

您应该Promise.all()按如下方式使用(未经测试):

  const promises = [];

  for (var i = 0; i < this.files.length; i++) {
    // files.values contains all the files objects
    const file = this.files[i];
    const storage = getStorage();
    const metadata = {
      contentType: "image/jpeg",
    };
    const storageRef = ref(storage, "temp/" + docRef.id + "/" + file.name);

    promises.push(uploadBytes(storageRef, file, metadata).then(uploadResult => {return getDownloadURL(uploadResult.ref)}))
    
  }

  const photos = await Promise.all(promises);

  await console.log(photos);
  await updateDoc(docRef, { photosURLs: photos }); // <= See the change here docRef and not docRef.id
Run Code Online (Sandbox Code Playgroud)