Upload a file to Firebase storage using vue.js

0

I have an html file that receives the file through an input

<div class="form-group col-sm-12">
  <label>Adjunte la copia de la cedula de conyuge en formato PDF</label>
  <input type="file" ref="cedulaTrabajador" @change="agregar" accept="image/jpeg" class="form-control" id="archivoCedulaConyuge"  data-validate="Anexe la copia de su cedula">
</div>

I would like if someone could tell me how I can upload a file using vue to firebase storage

    
asked by Marteen Munevar 27.11.2018 в 22:51
source

1 answer

0

If you are using vue-cli and NPM you need to install the firebase library and configure the credentials of your firebase project in the file /src/main.js of the following way.

import Vue from 'vue'
import App from './App.vue'
import firebase from 'firebase/app'

Vue.config.productionTip = false

// llenar con las credenciales de tu proyecto firebase
firebase.initializeApp({
  apiKey: '',
  authDomain: '',
  databaseURL: '',
  projectId: '',
  storageBucket: '',
  messagingSenderId: '',
});

new Vue({
  render: h => h(App),
}).$mount('#app')

Then in the file .vue , where your input implements a code similar to the following:

  

Note: To be able to save files in firebase storage you must configure the write and read permissions in your project firebase .

<template>
  <div class="form-group col-sm-12">
    <label>Adjunte la copia de la cédula de conyuge en formato PDF</label>
    <input
      type="file"
      ref="cedulaTrabajador"
      accept="application/pdf"
      :disabled="loading"
      class="form-control"
      id="archivoCedulaConyuge"
      data-validate="Anexe la copia de su cédula"
    >
    <br>
    <button :disabled="loading" @click="agregar">Subir Archivo</button>
    <p v-if="downloadUrl">
      Archivo disponible en:
      <a :href="downloadUrl">Link</a>
    </p>
  </div>
</template>
<script>
import firebase from 'firebase/app';
import 'firebase/storage';

export default {
  data() {
    return {
      loading: false,
      downloadUrl: ''
    };
  },
  methods: {
    async agregar() {
      try {
        const { files } = this.$refs.cedulaTrabajador;
        this.loading = true;
        const file = files[0];
        if (file) {
          const isPdf = file.type === 'application/pdf';
          if (isPdf) {
            const response = await firebase
              .storage()
              .ref('pdfs/${file.name}')
              .put(file);
            const url = await response.ref.getDownloadURL();
            console.log('archivo disponible en ', url);
            this.downloadUrl = url;
          } else {
            console.log('Archivo no valido');
          }
        } else {
          console.log('falta el archivo');
        }
      } catch (error) {
        console.error(error);
      }
      this.loading = false;
    }
  }
};
</script>
    
answered by 09.12.2018 / 11:30
source