简体   繁体   English

如何将 firebase storage downloadURL 保存到 firestore 集合?

[英]How to save firebase storage downloadURL to firestore collection?

I'm unable to save my firebase storage image into a firestore collection variable.我无法将我的 firebase 存储图像保存到 firestore 集合变量中。 It was working fine for some time but then stopped working.它工作了一段时间,但后来停止工作。 The image variable returns null.图像变量返回空值。

ps - I'm using the asia-south1 server ps - 我正在使用 asia-south1 服务器

Here's my template code for ManageProducts这是我的 ManageProducts 模板代码

<div>
      <h1>Add Items</h1>
      <div>
        <form>
          <input type="text" placeholder="name" required v-model="item.name" />
          <textarea
            required
            placeholder="description"
            v-model="item.description"
          ></textarea>
          <input
            type="text"
            required
            placeholder="price"
            v-model="item.price"
          />
          <div class="form-group">
            <input
              type="text"
              placeholder="Available/Unavailable"
              v-model.lazy="item.status"
              class="form-control"
            />
          </div>
          <div class="form-group">
            <input
              type="text"
              placeholder="Sewing Partner"
              v-model.lazy="item.sewingPartner"
              class="form-control"
            />
          </div>
          <input type="file" required @change="uploadImage" accept="image/*" />
          <button @click.prevent="AddNewItem">Add Item</button> |
          <button class="delete">
            Cancel
          </button>
        </form>
      </div>

Here's the script for Manage Products.这是管理产品的脚本。 In here, I'm able to add all the other input values except for the firebase storage's image Url.在这里,我可以添加除 firebase 存储的图像 Url 之外的所有其他输入值。

  <script>
    import { dbItemAdd } from "../../main";
    import firebase from "firebase";
    import "firebase/firestore";
    import "firebase/storage";
    export default {
      name: "AddItems",
      components: { AdminPreviewItems },
      data() {
        return {
          items: [],
          item: {
            name: null,
            description: null,
            image: null,
            price: null,
            status: null,
            sewingPartner: null,
          },
        };
      },
      methods: {
        uploadImage(e) {
          let file = e.target.files[0];
          var storageRef = firebase.storage().ref("products/" + file.name);
          let uploadTask = storageRef.put(file);
          uploadTask.on(
            "state_changed",
            (snapshot) => {
              console.log(snapshot);
            },
            (error) => {
              // Handle unsuccessful uploads
              console.log(error.message);
            },
            () => {
              // Handle successful uploads on complete
              // For instance, get the download URL: https://firebasestorage.googleapis.com/...
              uploadTask.snapshot.ref.getDownloadURL().then((downloadURL) => {
                this.item.image = downloadURL;
                console.log("File available at", downloadURL);
              });
            }
          );
        },
    
        AddNewItem() {
          dbItemAdd
            .add({
              name: this.item.name,
              description: this.item.description,
              image: this.item.image,
              price: this.item.price,
              status: this.item.status,
              sewingPartner: this.item.sewingPartner,
            })
            .then(() => {
              location.reload();
              console.log("Adding data to Firestore");
            })
            .catch((error) => {
              console.error("Error adding document: ", error);
            });
        },
      },
    };
    </script>

When are you calling the AddNewItem function?你什么时候调用AddNewItem函数? If the image is not uploaded yet or the downloadURL is not fetched, if you click the submit button it'll be null.如果图像尚未上传或未获取 downloadURL,如果您单击提交按钮,它将为空。

uploadTask.snapshot.ref.getDownloadURL().then((downloadURL) => {
  this.item.image = downloadURL;
  console.log("File available at", downloadURL);
  //function must be called after this
});

You can disable the submit button is this.item.image is null (default value).您可以禁用提交按钮是this.item.image为 null(默认值)。

<button :disabled="!item.image" @click.prevent="AddNewItem">Add Item</button>

I don't see state_changed observer being used.我没有看到使用state_changed观察者。 Do you need to show the upload progress?需要显示上传进度吗? If yes, keep the existing code as it is else I would refactor it as an async function like this:如果是,请保留现有代码,否则我会将其重构为这样的异步函数:

async uploadImage(e) {
  let file = e.target.files[0];
  if (!file) alert("No file selected")
  var storageRef = firebase.storage().ref("products/" + file.name);
  let uploadTask = await storageRef.put(file);
  const url = await storageRef.getDownloadURL()
  this.item.image = url
}

You are actually uploading the image on file change and not submit button click so you could add the Firestore document from the @change event itself right after getting downloadURL.您实际上是在文件更改时上传图像,而不是提交按钮单击,因此您可以在获取 downloadURL 后@change@change事件本身添加 Firestore 文档。

Once you upload a file to storage, you call the getDownloadURL() which will generate an access token将文件上传到存储后,调用getDownloadURL()将生成访问令牌

You then store this URL and access token directly into firestore然后,您将此 URL 和访问令牌直接存储到 firestore 中

// Create reference to image
var mountainImagesRef = storageRef.child('images/mountains.jpg');
// Put image file to Storage
ref.put(file).then((snapshot) => {
// On complete, get the downloadURL
return mountainImagesRef.getDownloadURL()})
.then((downloadURL) =>
// Add download URL to Firestore
firestore().doc("path/to/document/here").add({
              name: this.item.name,
              description: this.item.description,
              image: downloadURL,
              price: this.item.price,
              status: this.item.status,
              sewingPartner: this.item.sewingPartner,})
).catch(console.error);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从Firebase存储获取DownloadURL - How to get DownloadURL from Firebase Storage Vuejs + Firebase Storage 上传多张图片到 Firebase Storage 并将所有 downloadURL 推送到 Firestore - Vuejs + Firebase Storage upload multiply images into Firebase Storage and push all downloadURL into Firestore firebase/firestore 将用户保存到集合 - firebase/firestore save user to collection Firebase 存储 - 获取实际数据而不是 downloadURL - Firebase Storage - Get actual data instead of downloadURL 从 firebase 存储中获取每个文件的下载 URL - Get the downloadURL for each file from firebase storage Firebase 存储不返回 downloadURL - Firebase storage don't return downloadURL 将图像存储在Firebase存储中并在Firebase Cloud Firestore(Beta)中保存元数据 - Store image in Firebase Storage and save metadata in Firebase Cloud Firestore (Beta) 如何在使用 firebase 存储上传后获取调整大小的 downloadUrl(Web SDK + 调整图像扩展) - How to get the resized downloadUrl after upload with firebase storage (Web SDK + Resize images extention) 如何在 Firebase / Firestore 中创建用户时创建嵌套集合,用户可以在其中保存已添加书签的项目 - How to create a nested collection when creating a user in Firebase / Firestore where users can save bookmarked items 如何使用Firebase模拟器写入Firestore、Storage? - How to use Firebase Emulator to write to Firestore, Storage?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM