The functionality of getDownloadURL is not functioning as expected with Firebase Storage on the web platform

Having some trouble with my code as it does not seem to log the download URL of the file being uploaded. I am getting this error message:

GET ...{URL that is not the download URL}... 404()

This is the code snippet in question.

     //Get image
     var file = a.target.files[0];

     //create a storage reference
     var storageRef = firebase.storage().ref('images/' + file.name);

     //store the image
     var task = storageRef.put(file);

     var storage = firebase.storage();
     storageRef.child('images/'+file.name).getDownloadURL().then(function(url) {
        console.log(url);          
      }).catch(function(error) {
        // Handle any errors
      });

Any ideas on how to successfully retrieve the download URL?

Answer №1

When uploading a file, it's important to note that it is an asynchronous operation that may take some time to complete. If your code does not account for this, you might end up retrieving the download URL before the file has finished uploading.

The Firebase Storage documentation provides an example on how to upload files to Firebase Storage:

// Assuming we have a File or Blob named rivers.jpg
var file = ...

// Upload the file to 'images/rivers.jpg'
// Utilize the File API's 'name' property to get the file name
var uploadTask = storageRef.child('images/' + file.name).put(file);

// Set up three observers:
// 1. 'state_changed' observer for tracking state changes
// 2. Error observer for handling failures
// 3. Completion observer for successful uploads
uploadTask.on('state_changed', function(snapshot){
  // Track progress, pause, and resume events here
}, function(error) {
  // Handle failed uploads
}, function() {
  // Process successful uploads
  // Obtain the download URL: https://firebasestorage.googleapis.com/...
  var downloadURL = uploadTask.snapshot.downloadURL;
});

In this example, the download URL is retrieved only after the upload process is complete.

If you're not concerned with monitoring progress and errors, you can simplify it like so:

uploadTask.on('state_changed', null, null, function() {
  var downloadURL = uploadTask.snapshot.downloadURL;
});

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 are the implications of employing a singular global variable for angular modules?

After coming across a template, I noticed that the variable anApp is declared once in app.js and then shared among all modules. This has led me to wonder: 1. Will using a single variable result in all Angular components being stored in the global scope? 2. ...

Extract the image URL from a JSON API

I'm struggling to retrieve an image URL from a Wordpress JSON API and populate an image tag with it. Below is the code that isn't working for me: $(document).ready(function() { $.getJSON('http://interelgroup.com/api/get_post/?post_id=46 ...

Executing a Cron Job several times daily, each and every day

This is my current code snippet: const CronJob = require('cron').CronJob; new CronJob({ cursoronTime: '* * * * *', // every minute onTick: async function() { console.log(&ap ...

Generate HTML tags dynamically within a JSON document using PHP

Is there a way to incorporate HTML markups (generated dynamically by a CMS) into a JSON file? I am aware that in the html string, one must escape double quotes by adding "" as shown below. { "title": "Title", "da ...

script to pause video using jQuery

I have a script that works perfectly, but currently it only stops an instance of a playing video if a new video is started. I want to modify the script so that ALL instances of playing videos are stopped when the function stopAllButMe(); is called. Can s ...

The JQuery CSS function is unable to alter the height of the element

I am working with a grid that contains various elements, each with the class item. When I click on one of these elements, I toggle the class expand to resize the element. <body> <div class="grid"> <a href="#"> < ...

Automatically submit form in Javascript upon detecting a specific string in textarea

Just getting started with JS and I have a question that's been bugging me. I have a simple form set up like this: <form method="POST" action="foo.php"> <textarea name="inputBox123"></textarea> <input type="submit" value="Go" name ...

The absence of an index signature in GenericType is causing a missing declaration of the expected key/value type in Flow type

I am encountering difficulties accessing an object property dynamically with a Generic Type. Below is the code snippet: import React, { useState } from 'react' function useForm<FormValues>(initialValues: FormValues) { const [formValue ...

CSS for when the mouse hovers over an element

Two php files and a js file are involved in this scenario. The issue at hand is that when the div is clicked, it navigates to a new page with an appended # to the URL, causing it to scroll to the specified comment ID. However, instead of scrolling to the c ...

Preventing a Click Event on Child Element from Triggering the Parent's Click Event in jQuery

Can you help me figure out how to prevent a button from executing the onclick function of its parent div in this example? <div onclick="$('#extra-info').slideToggle();" class="card card-body item"> <div class="ro ...

Tips for handling numerous observables in Angular 7

I am working on an Angular 7 application that deals with a total of 20 sensor data. My goal is to receive data from a selected sensor every 5 seconds using observables. For example: var sensorId = ""; // dynamically chosen from the web interface var senso ...

Tips for managing accordion events using a button press

I found a script online that I want to modify. Specifically, I am looking to create a button that will control the accordion event by closing the current div and opening the next one. <button> Click me to open next</button> inside each div in ...

Choosing an item using the mouse - Three.js

I have a question that I need help with. I'm trying to change the color of an object when it's selected with the mouse, but the code I wrote doesn't seem to be working correctly. Here's what I have so far: <script> v ...

Definitions have not been declared

My coding is as follows: var data = JSON.parse(http.responseText); var weatherData = new Weather(cityName, data); weatherData.temperature = data.main.temp; updateWeather(weatherData); function Weather(cityName, data) { this.cityName = cityNa ...

Having trouble retrieving the selected value from a dropdown list with Jquery

In my current setup, I have a drop-down list situated within a pop-up modal. The dropdown menu is structured like this: <select name="EventTypeId" class="form-control formTextBox" id="ddlEventType"> <option value="">Please Select</optio ...

Troubleshooting a rendering performance problem with an object rendered using Three.js

Having an issue with animations slowing down over time when rendering an obj file from Blender using Three.js. Here's the code snippet I'm working with: <script> var objcontainer, stats; var camera, scene, rendere ...

VueJS form validation does not account for empty inputs in both fields

One of the challenges I'm facing is generating a form with Vue.js using the input fields below: { name: 'first_name', type: 'text', label: 'First Name', placeholder: 'First Name', ...

A guide on embedding a jpg or png image into an HTML button

I need a button that includes an image. Here is the code I am using: <input type="submit" name="submit" src="images/stack.png" /> However, the image is not displaying on the button as intended. My goal is for the entire button to be the image. ...

Using Ramda to retrieve objects from an array by comparing them with each element in a separate array

I have two arrays: ids = [1,3,5]; The second array is: items: [ {id: 1, name: 'a'}, {id: 2, name: 'b'}, {id: 3, name: 'c'}, {id: 4, name: 'd'}, {id: 5, name: 'e'}, {id: 6, name: 'f'} ]; I ...

Poor initial placement of the Dialogs when the content exceeds the space available

While using material-ui^0.20 with react^16.2, I encountered an issue when initially displaying a Dialog containing a Component with excessive content. The problem is illustrated in this image: https://i.sstatic.net/RF8Mu.png This is the expected appeara ...