使用Vuejs获取Firebase存储中上传文件的URL

时间:2020-05-24 18:47:40

标签: javascript firebase vue.js firebase-storage

我的脚本有一个小错误, 我正在尝试使用vuejs将文件上传到Firebase存储,除了url为null外,其他所有方法都有效,我的脚本是一种账面价值形式,其中包含id,titre,description,prix_d,pdf(是文件),pdf_url和上传的值是脚本

import firebase from "firebase";
import db from "./firebaseInit";
export default {
  name: "vendre",
  data : ()=>{
    return {
      id_livre: null,
      titre: null,
      description: null,
      prix_d : null,
      pdf : null,
      pdf_url : null,
      uploadValue : null
    }
  },
  methods:{

    onfileSelected(event){
      this.pdf_url = null;
      this.pdf = event.target.files[0]
      console.log(event);
    },
  

    saveBook(){
      this.pdf_url = null;
      const storageRef = firebase.storage().ref(`${this.pdf.name}`).put(this.pdf);
      storageRef.on(`state_changed`,snapshot=>{
          this.uploadValue = (snapshot.bytesTransferred/snapshot.totalBytes)*100;
      }, error=>{console.log(error.message)}, ()=>{this.uploadValue =100;
        storageRef.snapshot.ref.getDownloadURL().then((url)=>{
          this.pdf_url = url;
        })
      })
      console.log(this.pdf_url);

      db.collection('Livres').add({
        id_livre : this.id_livre,
        titre : this.titre,
        description : this.description,
        url: this.pdf_url  
      }).then(docRef =>{ this.$router.push('/');console.log(docRef)}
      ).catch(error =>console.log(error.message))
    }
  }
};

1 个答案:

答案 0 :(得分:2)

获取文件的下载URL需要对服务器进行异步调用。因此,任何需要下载URL的代码都必须在 内,该URL在检索该URL时触发。

类似这样:

saveBook(){
  this.pdf_url = null;
  const storageRef = firebase.storage().ref(`${this.pdf.name}`).put(this.pdf);
  storageRef.on(`state_changed`,snapshot=>{
      this.uploadValue = (snapshot.bytesTransferred/snapshot.totalBytes)*100;
  }, error=>{console.log(error.message)}, ()=>{this.uploadValue =100;
    storageRef.snapshot.ref.getDownloadURL().then((url)=>{
      db.collection('Livres').add({
        id_livre : this.id_livre,
        titre : this.titre,
        description : this.description,
        url: url  
      }).then(docRef =>{ this.$router.push('/');console.log(docRef)
      }).catch(error =>console.log(error.message))
    })
  })
}