Firestore is a super easy way to configure your backend. Firestore provides a range of services anywhere from a database, user authentication, to using machine learning for many use-cases.
One of the many things you do in a typical app is to enable users to store files. While some find it easier to store files in database (huh?), the most popular option is to store files and reference them in the database record.
Firestore provides easy access to a service known as Firebase Storage to store files. Let’s see how.
Create Vue View
We get started with a simple Vue app (which is using Vuetify, but that does not matter)..
importfirebasefrom"firebase/app";import"firebase/storage";// get config from Firebase console
constfirebaseConfig={apiKey:"the_api_key",authDomain:"myapp.firebaseapp.com",databaseURL:"https://myapp.firebaseio.com",projectId:"myapp",storageBucket:"myapp.appspot.com",messagingSenderId:"12345",appId:"1:123512:web:1abcd23",measurementId:"G-123COOL",};firebase.apps&&!firebase.apps.length?firebase.initializeApp(firebaseConfig):"";exportconstFirebaseStorage=firebase.storage();exportdefaultfirebase;
We add the above code as a service instead of using them locally in components (or views) since we may need the same code in multiple places.
A few key points to note -
Get configuration from your Firebase console. This forms the entirety of firebaseConfig object
We export FirebaseStorage (alongside firebase) and this a ready-to-use service to access the Firebase storage
In the next section you will see how we use this service.
Add Method to Upload File
Finally, add the methods to handle image uploads in the view.
<script>import{FirebaseStorage}from"@/services/firebase.js";exportdefault{data(){return{myFile:null,processing:false,fileURL:null,};},methods:{asyncfileInput(file){try{if(file&&file.name){this.processing=true;constfr=newFileReader();fr.readAsDataURL(file);fr.addEventListener("load",()=>{// this is to load image on the UI
// .. not related to file upload :)
this.fileURL=fr.result;});constimgData=newFormData();imgData.append("image",this.myFile);constfilePath=`mypath/${Date.now()}-${file.name}`;constmetadata={contentType:this.myFile.type};awaitFirebaseStorage.ref().child(filePath).put(this.myFile,metadata);console.log("filePath: ",filePath);}}catch(e){console.error(e);}finally{this.processing=false;}},},};</script>
We are doing a few simple things here -
We read the file using const fr = new FileReader(); and display the file on the UI. This is just a “nice to have” feature to provide feedback to user when she selects the file
The selected file gets appended to form data - const imgData = new FormData()
Upload the file to the path const filePath = ``mypath/${Date.now()}-${file.name}``; on our Firebase storage using FirebaseStorage.ref()
That is it! You can now upload any file to Firestore (provided your security rules allow you to upload files).