Ad

How Can I Upload An Image To Firebase Storage And Add It To The Database?

I'm new to Vuejs. I want to have a form using which you can add products. The product image goes to firebase storage but how do I associate that image with the exact product in the database?

I've already set up my form, and created two methods. saveProduct() to save the products to the database and onFilePicked() to listen for changes in the input field and target the image and upload that to storage.

import { fb, db } from '../firebaseinit'
export default {
  name: 'addProduct',
  data () {
    return {
      product_id: null,
      name: null,
      desc: null,
      category: null,
      brand: null,
      image: null,
    }
  }, 
  methods: {
    saveProduct () {
      db.collection('products').add({
        product_id: this.product_id,
        name: this.name,
        desc: this.desc,
        category: this.category,
        brand: this.brand
      })
      .then(docRef => {
        this.$router.push('/fsbo/produkten')    
      })

    },
    onFilePicked (event) {
      let imageFile = event.target.files[0]
      let storageRef = fb.storage().ref('products/' + imageFile.name)
      storageRef.put(imageFile)
    }  
  }
}
Ad

Answer

I fixed it myself. Here's my solution. I don't know if it's technically correct but it works for my use case.

methods: {
saveProduct () {
  let imageFile
  let imageFileName
  let ext 
  let imageUrl
  let key
  let task
  db.collection('products').add({
    product_id: this.product_id,
    name: this.name,
    desc: this.desc,
    category: this.category,
    brand: this.brand
  })
  .then(docRef => {
    key = docRef.id
    this.$router.push('/fsbo/produkten')
    return key    
  })
  .then(key => {
    if(this.image !== null) {
      this.onFilePicked
      imageFile = this.image
      imageFileName = imageFile.name
      ext = imageFileName.slice(imageFileName.lastIndexOf('.'))
    }
    let storageRef = fb.storage().ref('products/' + key + '.' + ext)
    let uploadTask = storageRef.put(imageFile)
    uploadTask.on('state_changed', (snapshot) => {}, (error) => {
      // Handle unsuccessful uploads
    }, () => {
      uploadTask.snapshot.ref.getDownloadURL().then( (downloadURL) => {
        db.collection('products').doc(key).update({ imageUrl: downloadURL})
      });
    });     
  })    
},
onFilePicked (event) {
  return this.image = event.target.files[0]
}  

}

Ad
source: stackoverflow.com
Ad