I'm having trouble pulling images from Firebase into my Vue application

Currently, I am experimenting with a Vue application that requires users to upload an image to Firebase. After the image is successfully uploaded, it should be displayed within an img tag in the template.

The issue I am encountering is retrieving the uploaded images and displaying them properly within the application. I have tried implementing a method from Stack Overflow, but it doesn't seem to work for me.

I also looked through various tutorials, but they mainly focus on the uploading process rather than the display afterwards.

Is there anyone who could provide some assistance?

UPDATE:

I made progress by changing the v-for attribute from file to imgURL, which allowed me to preview the uploaded image. However, I am still facing challenges.

Despite seeing the image preview when I click the upload button (albeit 130 times), it disappears upon page refresh as it is not being saved in the template.

<template>
<div>
    <h2>image upload</h2>
    <input type="file" @change="uploadImage" value="upload" id="fileButton" ref="myFiles">
    <div class="image_section_content" fluid v-for="files in file" :key="files.id">
        <b-img :src="this.imgURL" fluid alt="Responsive image"></b-img>
        <progress max="100" :value="value" id="uploader">0%</progress>
    </div>
</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;

            console.log(this.imgURL)
         }
      )
    })
  },
  // Output image
    mounted() {
    const id = this.$route.params.id;
    const storageRef = firebase.storage().ref('images/');

    storageRef.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)
    })
  }
}

}

Answer №1

To handle this situation, establish a collection named imgUrl in Firestore to store the image URL and access them within the created() method.

  task.on('state_changed', (snapshot) => {
                let percent = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
                this.progress = percent;

                snapshot.ref.getDownloadURL().then(
                    (downloadedURL) => {
                        this.imageURL = downloadedURL;

                        db.collection("imgUrl").add({
                         url: this.imageURL
                         })
                    }
                )
            })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Posting data using an Ajax form submission without the need for page

After numerous attempts, I am still facing an issue where clicking the Submit button causes the page to refresh. What changes should I make to resolve this problem? <script> $('#submit').on('submit', function(event) { event.pre ...

What other strategies can I utilize to enhance my bundle and boost webpage loading time?

In my React application, I've utilized various libraries like redux, redux-form, react-router, leaflet, react-bootstrap, redux-thunk, and more. The minified bundle size is 531kb, while the vendor file stands at 5.32mb. For bundling and optimization, ...

What is the best way to incorporate personalized events into an array using JavaScript?

Imagine we have an array called var arr = [1, 2, 3]. I am looking for a way to create a method that can observe any changes made to this array. The idea is something similar to the following: arr.on('change', function () { // perform some ac ...

The mysterious unknown variable dynamically imported: ../views/Admin/Home.vue in Vue3-vue-router4 has sparked curiosity

When utilizing Vue3, Vuerouter4, and Vite I am attempting to import components and routes into the vue router, but I am encountering an error (only for the route that contains children in my paths): This is my router code: import { createRouter, crea ...

Having trouble retrieving information from a nested JSON array within a JSON object using JavaScript

I am facing a challenge with extracting specific information from a JSON object that contains an array nested inside. Even though I have experience working with JSON arrays, this particular object is proving to be tricky. For example, when attempting to r ...

Implementation of Material UI Autocomplete feature with options consisting of an array of objects linking to both ID and label properties

Utilizing the Material UI Autocomplete component in my project has been a key feature. Referencing the official documentation, here are the available options: let options = [ { id: "507f191e810c19729de860ea", label: "London" }, { id: "u07f1u1e810c19 ...

I am looking for a way to display or conceal text depending on the presence of an image

Could you please help me with this? I am looking for a solution where text is displayed only when there is content in the src attribute of an img tag. Essentially, I need JavaScript code that can identify if an attribute has content and then make a paragra ...

I am unable to append a new attribute to an object

I am currently working on a project using Node, Express, and Mongoose. In my controller, I'm trying to retrieve all orders for the logged-in client from the database. I want to display the status of each order and based on the state, add the available ...

Is there a way to make my for loop search for the specific element id that I have clicked on?

When trying to display specific information from just one array, I'm facing an issue where the for loop is also iterating through other arrays and displaying their names. Is there a way to only show data from the intended array? const link = document. ...

Establish a new <section> to serve as a distinct webpage

I have a question about creating multiple <section> elements on a page. I am looking to build an HTML document with several <section> tags, as outlined below. <html> <head> </head> <body> <sectio ...

Editing DOM elements within Angular JS using Greasemonkey extension

I have been developing a Greasemonkey script to enhance the performance of a vendor's angularJS tool by automating certain processes. One major obstacle I am encountering is that the element I need to interact with is not yet loaded in the DOM when m ...

Is it possible to utilize getInitialProps in both _app.js and in individual pages within the application?

I am currently developing my first significant NextJS application. Instead of hardcoding the left navigation data directly into the app, I have set it up to pull in JSON data. This allows me to make minor changes to the site's navigation without havin ...

Issue with Firefox browser: Arrow keys do not function properly for input tags in Twitter Bootstrap drop down menu

Requirement I need to include a login form inside the dropdown menu with username and password fields. Everything is working fine, except for one issue: Issue When typing, I am unable to use the arrow keys (up/down) in Firefox. This functionality works ...

How much worth does an unfilled text input box hold?

I've been working on integrating a search feature and I'm having an issue with the functionality. Below is the code snippets for both HTML and JS: HTML <form> <input type="text" ng-model="searchVar" class="searchbox"> <in ...

What is the method for getting js_xlsx to include all empty headers while saving the file?

In the midst of developing a Meteor App, I've incorporated the Node.js package known as "js_xlsx" from "SheetJS", produced by "SheetJSDev". This tool enables me to convert an Excel sheet uploaded into JSON on the backend. The intention is to store thi ...

There is a JSON issue present, with half of the variables being undefined

Having an issue with my JSON as it throws me an undefined error. What's puzzling is that it recognizes my first variable without any problem. Below are the codes for better understanding: JSON {"Comics":[ {"comic" : { "src":"Pictures/Comic ...

Remove the export statement after transpiling TypeScript to JavaScript

I am new to using TypeScript. I have a project with Knockout TS, and after compiling it (using the Intellij plugin to automatically compile ts to js), this is my sample.ts file: import * as ko from "knockout"; ko; class HelloViewModel { language: Kn ...

Angular/Karma Unit Test for HttpClient

During my research on unit testing, I came across some very useful examples. Most of the examples focus on unit testing functions that interact with Angular's HttpClient, and they usually look like this: it('should return an Observable<User[] ...

The play button on the iOS video player will be deactivated automatically after watching 15 videos

I have developed an application using the Ionic Framework that includes multiple videos for playback. To organize these videos, I created a category system where users can click on a video title to access the corresponding video player page. The video pla ...

VueTablePlus dropdown filter options for Vue.js version 2

I am facing an issue with populating dropdown options on vue good table. My approach involves making an API call to fetch the possible values for the dropdown and then assigning them to the column filter. However, I am struggling to make it work. <vue ...