Using Firebase with Vue for File Uploads

Jun 4, 2021

Firebase is an easy backend to store uploaded files, and it works great with Vue. You can npm install firebase firebase-storage or use a CDN. You need the firebase-storage package to store files. If you want to disable authentication, you will need to change in the storage rules as shown below, from:

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth != null;
    }
  }
}

To:

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth != true;
    }
  }
}

Once that's done, you can modify the code from this article as follows:

<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/8.6.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.3/firebase-storage.js"></script>
<script>
  const firebaseConfig = {
    apiKey: "",
    authDomain: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: "",
    measurementId: "",
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);
</script>
<div id="content"></div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12"></script>
<script>
  const app = new Vue({
    data: () => ({ File: null, value: null, preview: null, isPic: false }),
    template: `
      <div style="border-style:solid">
        <input type="file" @change="getFile()"/>
        <button @click="submitFile">Upload!</button>
        <div v-if="!isPic">
        {{preview}}
        </div>
        <div v-else>
        <img :src="preview" style="width:75%"/>
        </div>
      </div>
    `,
    methods: {
      getFile() {
        this.File = event.target.files[0];
        this.preview = null;
        this.isPic = false;
        if (
          this.File.name.includes(".png") ||
          this.File.name.includes(".jpg")
        ) {
          this.isPic = true;
        }
      },
      submitFile() {
        const storage = firebase.storage().ref().child(`${this.File.name}`);
        const storageRef = storage.put(this.File);
        setTimeout(() => {
          storage.getDownloadURL().then((res) => (this.preview = res));
        }, 3000);
      },
    },
  });
  app.$mount("#content");
</script>

Here is a live demo that will display the url when the file is uploaded and display a preview if it is an image:


Vue School has some of our favorite Vue video courses. Their Vue.js Master Class walks you through building a real world application, and does a great job of teaching you how to integrate Vue with Firebase. Check it out!


Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Vue Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!