I have a Vue project, where the user needs to be able to upload an image to Firebase storage and then retrieve it so that it is saved inside an img tag on the webpage.
So far I have managed to make a code that allows me to upload an image to a Firebase storage folder. After that, the image URL is saved inside a collection in a Firestore database. I then tell the program to get that image URL and display it inside the Vue component.
The problem is that once I refresh the page, the image will get deleted.
So what I am trying to figure out is how to save the file so that it stays on the page even after refreshing.
Here is the full code:
<template>
<div class="upload" >
<h2>image upload</h2>
<div class="imgContainer">
<b-img :src="this.imgURL" fluid alt="Responsive image"></b-img>
</div>
<progress max="100" :value="value" id="uploader">0%</progress>
<input @change="uploadImage" type="file" value="upload" id="fileButton" ref="myFiles">
</div>
</template>
<script>
import db from '@/firebase/init'
import firebase from 'firebase'
export default {
name: 'ImageUpload',
data () {
return {
value: 0,
fileButton: document.querySelector("#fileButton"),
file: [],
imgRef: null,
imgURL: null
}
},
methods: {
uploadImage(e){
//get file
this.file = this.$refs.myFiles.files[0]
console.log(this.file)
//create storageref
let storageRef = firebase.storage().ref('images');
//save image reference
this.imgRef = storageRef.fullPath;
//upload file
let task = storageRef.put(this.file);
task.on('state_changed', (snapshot) => {
let percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
this.value = percentage;
snapshot.ref.getDownloadURL().then(
(DownloadURL) => {
this.imgURL = DownloadURL;
db.collection("images").add({
url: this.imgURL
})
}
)
})
},
// Output image
mounted() {
const id = this.$route.params.id;
const imageFile = db.collection("images");
imageFile.get().then(doc => {
if (doc.exists) {
console.log(doc.data())
this.imgURL = doc.data().imgURL
} else {
console.log('no data')
}
}).catch(err => {
console.log(err)
})
}
}
}
</script>
What I have tried:
In previous Vue projects, when saving data from a database, I have made a created method and rendered the files from the database inside an element with v-for.
I tried to do the same with this code, but it did not work.
I tried the following:
<div class="imgContainer" v-for="files in file" :key="files.id">
<b-img :src="this.imgURL" fluid alt="Responsive image"></b-img>
</div>
and
created() {
db.collection('images').get()
.then(snapshot => {
snapshot.forEach(doc => {
let ImageUpload = doc.data()
files.id = doc.id
this.image-upload.push(files)
})
})
}