【问题标题】:Get url of uploaded file in firebase storage with Vuejs使用 Vuejs 在 Firebase 存储中获取上传文件的 url
【发布时间】:2020-09-11 09:43:36
【问题描述】:

我的脚本有一个小错误, 我正在尝试使用 vuejs 将文件上传到 firebase 存储,除了 url 为空,我的脚本是一种账面价值形式,其中包含 id、tire、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))
    }
  }
};

【问题讨论】:

    标签: javascript firebase vue.js firebase-storage


    【解决方案1】:

    获取文件的下载 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))
        })
      })
    }
    

    【讨论】:

      猜你喜欢
      • 2017-07-08
      • 2021-05-11
      • 2018-12-28
      • 2021-03-11
      • 2019-06-20
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 2020-06-14
      相关资源
      最近更新 更多