【问题标题】:How to delete images from Firestore with Vue.js component如何使用 Vue.js 组件从 Firestore 中删除图像
【发布时间】:2019-12-13 12:41:16
【问题描述】:

我正在尝试重新利用我之前找到的 Vue.js 图像上传器组件 (https://codesandbox.io/s/219m6n7z3j)。该组件支持将图像上传到 Firebase 存储,以及将下载 URL 保存到 firestore,以便即使在刷新后图像也能持续呈现在屏幕上。我一直在尝试向组件添加 deleteImg() 方法,但出现错误:

FirebaseError: Function CollectionReference.doc() 要求其第一个参数为非空字符串类型,但它是:未定义

关于如何设置deleteImg() 方法以便从存储和数据库中删除图像的任何建议?

<template>
  <div id="app">
    <v-toolbar color="indigo" dark fixed app>
      <v-toolbar-title>Vue Firebase Image Upload</v-toolbar-title>
    </v-toolbar>
    <v-app id="inspire">
      <v-content>
        <v-container fluid>
          <v-layout align-center justify-center>
            <v-flex xs12 sm8 md4>
              <img :src="imageUrl" height="150" v-if="imageUrl" />
              <v-text-field label="Select Image" @click="pickFile" v-model="imageName"></v-text-field>
              <input type="file" style="display: none" ref="image" accept="image/*" @change="onFilePicked"/>
              <v-btn color="primary" @click="upload">UPLOAD</v-btn>
            </v-flex>
          </v-layout>
          <br />

          <v-layout align-center justify-center>
            <v-flex xs12 sm8 md4>
              <div v-for="img in imgUrls" :key="img.id">
                <br />
                <img :src="img.downloadUrl" height="150" />
                <v-btn @click="deleteImg(img.id)">x</v-btn>
              </div>
            </v-flex>
          </v-layout>
        </v-container>
      </v-content>
    </v-app>
  </div>
</template>

<script>
import firebase from 'firebase'
import { db } from "./main";

export default {
  name: "App",
  data() {
    return {
      photo: null,
      photo_url: null,
      dialog: false,
      imageName: "",
      imageUrl: "",
      imageFile: "",
      imgUrls: []
    };
  },
  created() {
    this.getImages();
  },
  methods: {
    getImages: function() {
      db.collection("images")
        .get()
        .then(snap => {
          const array = [];
          snap.forEach(doc => {
            array.push(doc.data());
          });
          this.imgUrls = array;
        });
      this.imageName = "";
      this.imageFile = "";
      this.imageUrl = "";
    },

    pickFile() {
      this.$refs.image.click();
    },

    onFilePicked(e) {
      const files = e.target.files;
      if (files[0] !== undefined) {
        this.imageName = files[0].name;
        if (this.imageName.lastIndexOf(".") <= 0) {
          return;
        }
        const fr = new FileReader();
        fr.readAsDataURL(files[0]);
        fr.addEventListener("load", () => {
          this.imageUrl = fr.result;
          this.imageFile = files[0]; // this is an image file that can be sent to server...
        });
      } else {
        this.imageName = "";
        this.imageFile = "";
        this.imageUrl = "";
      }
    },

    upload: function() {
      var storageRef = firebase.storage().ref();
      var mountainsRef = storageRef.child(`images/${this.imageName}`);
      mountainsRef.put(this.imageFile).then(snapshot => {
        snapshot.ref.getDownloadURL().then(downloadURL => {
          this.imageUrl = downloadURL;
          const bucketName = "xxx-xxxx-xxxxx.xxxxxxx.xxx";
          const filePath = this.imageName;
          db.collection("images").add({
            downloadURL,
            downloadUrl:
              `https://firebasestorage.googleapis.com/v0/b/${bucketName}/o/images` +
              "%2F" +
              `${encodeURIComponent(filePath)}?alt=media`,
            timestamp: Date.now()
          });
          this.getImages();
        });
      });
    },
    deleteImg(img) {
      db.collection("images").doc(img).delete()
      .then(() => {
        console.log('Document successfully deleted')
      })
      .then(() => {
        this.getImages()
      })
    }
  },
  components: {}
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

【问题讨论】:

    标签: javascript firebase vue.js google-cloud-firestore vuetify.js


    【解决方案1】:

    我猜doc.data()中没有id可用,你需要手动添加id

    getImages: function() {
      db.collection("images")
        .get()
        .then(snap => {
          const array = [];
          snap.forEach(doc => {
            const data = doc.data()
            array.push({
              id: doc.id,
              ...data
            });
          });
          this.imgUrls = array;
        });
      this.imageName = ""
      this.imageFile = ""
      this.imageUrl = ""
    },
    

    【讨论】:

    • 非常感谢!这特别适用于数据库中的文档。图像将从屏幕和 Firestore 数据库中删除。但是,图像仍保留在存储中。我试图向 deleteImg() 函数添加一个 .then() 承诺,该函数也会从存储中删除图像。我根据这个例子(firebase.google.com/docs/storage/web/delete-files)设置了 Promise。但是,我不确定如何配置此承诺以启用目标图像的删除。关于如何设置的任何提示?再次感谢!
    • @Frank van Puffelen,感谢您更新问题的布局。你能看一下下一个问题吗?我正在尝试启用从存储中删除图像的功能。关于如何设置的任何提示?谢谢!
    猜你喜欢
    • 2019-12-15
    • 2019-12-12
    • 2021-09-01
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    • 2017-08-21
    相关资源
    最近更新 更多