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

What is the best way to present JSON data retrieved from an API on different pages using Next.js?

I am currently working on two pages that are connected: one is an API page called secured.js (where user session data is processed) and the other is a normal page also named secured.js (which displays the processed content from the API page). This is the ...

Leveraging jQuery template for JSON visualization

I've been struggling for days to understand how to render JSON data using jQuery templates with no luck. I was hoping someone could help me figure out where I'm making a mistake. The JSON data I am working with looks something like this: [{"pk" ...

Troubleshooting a "Cannot GET" error while using Vue.js with a REST API

I am currently working on a project with Vue.js and I am running it locally through npm (Node). As a newcomer to Rest APIs, I followed an online tutorial to create a simple REST API. The file is named employees.php <?php // Establish database connect ...

Testing an asynchronous generator function in Jest using unit tests

I need help writing a unit test for a generator function where I am struggling to properly mock a read stream object (ReadStream). Here is the function I'm trying to test: public async *readChunks(file: string, chunkSize: number): AsyncIterableIter ...

Prevent fixed element from scrolling beyond a specific point

I'm working on a fixed sidebar that needs to scroll along with the main content and stop at a specific point when scrolling down, and vice versa when scrolling up. I've created a script that calculates the window height, current scroll position ...

A step-by-step guide on sending a fetch request to TinyURL

I have been attempting to send a post request using fetch to tinyURL in order to shorten a URL that is generated on my website. The following code shows how I am currently writing the script, however, it seems like it's not returning the shortened URL ...

Troubleshooting: Issue with AngularJS Image onload directive - "this" reference not functioning properly?

I have a custom directive that looks like this: .directive('ngImageOnLoad', function () { return { restrict: 'A', link: function(scope, element, attrs) { element.bind('load', function() { ...

A step-by-step guide to creating a delete feature for nested data in Laravel using Vue.js

My standard function format for deleting is not working on nested data. methods: { delete() { axios.delete('./../api/parent/' + this.parent.id) .then( response => { if( re ...

Automatically generate the first user on the Parse Server system

Is it feasible to programmatically create a User on Parse server without the need for sign up? More information can be found at https://github.com/parse-community/parse-server We attempted this using cloud code. var user = Parse.User(); user.setUserna ...

Obtain the identification address for a group of items

I have a JSON object containing place IDs, and I am attempting to retrieve the corresponding addresses for each ID. This is the code snippet I'm using: <div id="places" class="places"></div> <script> function initialize() { j ...

What are some methods to prevent cookies from being overridden?

Just beginning my journey in web development. Currently utilizing asp.net Web API and Angular with token authentication. Every time a user logs in, I set the token in a cookie and send it with each request. Everything has been running smoothly so far, bu ...

Using Vue router to dynamically define the query key when calling router.push()

Hello, I am relatively new to using Vue and have been working on a project that involves making GET requests based on the current URL. In one of my functions, I am trying to dynamically set the value of filterType in the query key within the router.push() ...

What specific types of errors is this try-catch block designed to catch and manage?

// This function establishes a connection to MongoDB using Mongoose const connectToDatabase = (url) => { return mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('Conn ...

Angular encountered an issue with an HTTP POST request, as the 'Access-Control-Allow-Origin' header was not found on the requested resource

I have been attempting to transmit data to a servlet using Angular HTTP POST requests. var httpPostData = function (postparameters, postData){ var headers = { 'Access-Control-Allow-Origin' : '*', &a ...

Optimizing NodeJS for scheduling and sending bulk text messages based on MongoDB data

I am currently developing an application that relies on MongoDB database entries to send text messages through AWS. The information stored in the database includes the message content, phone number, and scheduled time for sending the message. As of now, ...

When using Vue 3 with Laravel Blade template, issues arise when trying to generate a production build

When working with Vue 3 SFC and trying to embed the template inside a Laravel Blade file, it can be a bit tricky. Take for example this usage scenario: Test.vue <script setup> import { ref} from 'vue'; const testValue = ref('Works&a ...

Choosing options from an API response in a REACT-JS application

I have a Select Component in my application and I want it to automatically show the selected data once the response is received. import Select from "react-select"; <Select menuPlacement="auto" menuPosition="fixed" ...

What is the best way to distribute components between two NextJS projects?

Confused about the best way to share ReactJs components between two NextJs applications - one for e-commerce and the other for a manager portal. In the e-commerce app, there are various UI components that I want to reuse in the manager portal. Considering ...

Using 'interface' declarations from TypeScript is unsupported in JS for React Native testing purposes

I have a ReactNative app and I'm attempting to create a test using Jest. The test requires classes from a native component (react-native-nfc-manager), and one of the needed classes is defined as follows export interface TagEvent { ndefMessage: N ...

Reacting with Node.js: Capturing a selected option from a dropdown menu and storing it in the database

On my React frontend, I have a select dropdown like this: <select name="level" value={level} onChange={this.handleChange} className="form-control"> <option>Begineer</option> <option>Intermediate</option> <option> ...