Firebase Storage getDownloadUrl() "is not a function" - javascript

let storage = firebase.storage();
let storageRef = storage.ref("EnglishVideos/" + movieTitle + "/" + movieTitle + "_full.mp4");
console.log(storageRef); // looks OK, no error messages
The above code works, the object returned from Firebase Storage has the correct location, no error messages.
But getDownloadUrl() doesn't work:
let myURL = storageRef.getDownloadUrl();
console.log(myURL); // TypeError: storageRef.getDownloadUrl is not a function
The error is TypeError: storageRef.getDownloadUrl is not a function. It seems like a prototype chain bug. I'm using AngularJS, maybe I didn't inject a necessary dependency into my controller? I injected $firebaseStorage into the controller but it didn't help. My calls to Firebase Realtime Database from this controller are working fine.

It's getDownloadURL, not getDownloadUrl. Capitalization. My working code is
var storageRef = firebase.storage().ref("EnglishVideos/" + movieTitle + "/" + movieTitle + "_full.mp4");
storageRef.getDownloadURL().then(function(url) {
console.log(url);
});
The "official" version is
var storageRef = firebase.storage.ref("folderName/file.jpg");
storageRef.getDownloadURL().then(function(url) {
console.log(url);
});
Note that I needed a () after storage, i.e., storage().

#Thomas David Kehoe's solution got me nearly there.
I was still getting the error:
ERROR TypeError: storageRef.getDownloadURL(...).then is not a function
Here's my solution:
import { Observable } from 'rxjs';
and then inside my function:
var storageRef = this.storage.ref('myFolder/myFile.jpg');
storageRef.getDownloadURL().toPromise().then(function (url) {
console.log(url);
});

In my case, i was trying to call getDownloadURL(); on the upload task i.e
var upload=storage.child(`Testing/abc.png`).put(chosenFile);
//.....
//.....
upload.getDownloadURL();
solved it by doing
var ImgUploadRef=storage.child(`Testing/abc.png`);
var upload = ImgUploadRef.put(chosenFile);
//....
//....
ImgUploadRef.getDownloadURL();

Related

Load Image/Video from IndexedDB

I am working on a PWA project where I have created an IndexedDB and stored the images and videos in it. On the next reload of page, if image/video is available in IndexedDB, it should load it from there.
function fetchMedia(id) {
var transaction = db.transaction(["media"]);
var objectStore = transaction.objectStore("media");
var request = objectStore.get(id);
request.onerror = function(event) {
console.log("Unable to retrieve daa from database!");
return "";
};
request.onsuccess = function(event) {
var imgFile = request.result;
console.log(imgFile)
var imgURL = window.URL.createObjectURL(imgFile);
return imgURL;
};
}
It always returns undefined.
When I console.log the imgFile, it shows that it's there in the IndexedDB:
File in IndexedDB:
I have also tried this but no success yet:
var imgURL = window.URL.createObjectURL(new Blob(imgFile, {'type': 'application/octet-stream'}));
What's the correct approach to load the files from IndexedDB?
If your screenshot is accurate, then request.result is not an image, it's an object {id: '13388-7247-6247-62584', file: Blob, ...}. You didn't just store the image file, you wrapped it in an object. So what you're getting back out is an object.
Try imgFile = request.result.file; instead.
You cannot return inside the callback, you should wrap it in a promise.

How to read a file from an Azure Function in NodeJS?

I have an Azure function and a file called configAPI.json which are located in the same folder as shown in the image below.
I want to read the latter with the following code based on this post How can i read a Json file with a Azure function-Node.js but the code isn't working at all because when I try to see if there's any content in the configAPI variable I encounter undefined:
module.exports = async function (context, req) {
const fs = require('fs');
const path = context.executionContext.functionDirectory + '//configAPI.json';
configAPI= fs.readFile(path, 'utf-8', function(err, data){
if (err) {
context.log(err);
}
var result = JSON.parse(data);
return result
});
for (let file_index=0; file_index<configAPI.length; file_index++){
// do something
}
context.log(configAPI);
}
What am I missing in the code to make sure I can read the file and use it in a variable in my loop?
functionDirectory - give you path to your functionS app then you have your single function
I think you should do:
const path = context.executionContext.functionDirectory + '\\configAPI.json';
In case you want to parse your json file you should have:
const file = JSON.parse(fs.readFileSync(context.executionContext.functionDirectory + '\\configAPI.json'));
PS. context has also variable functionName so other option to experiment would be:
const path = context.executionContext.functionDirectory +
+ '\\' +context.executionContext.functionName + '\\configAPI.json';

Add file reference into database

I want to add the image reference of my uploaded image into firestore database. My code is uploading the image into the firebase storage but not save the data into the database. I am getting the error:
Uncaught FirebaseError: Function DocumentReference.set() called with invalid data. Unsupported field value: a custom je object (found in field Image)
What is the correct way to do this?
Please see codes below:
console.log("Initialisation Successful!");
var db = firebase.firestore();
var storageRef = firebase.storage().ref().child('Images');
function addExercise(){
var exerciseName = document.getElementById("ename").value;
var exercisePart = document.getElementById("body_part").value;
var exerciseLevel = document.getElementById("elevel").value;
var file = document.getElementById("eimage").files[0];
var thisRef = storageRef.child(file.name);
thisRef.put(file).then(function(snapshot) {
console.log('done!' + thisRef );
});
db.collection("Exercises").add({
Name: exerciseName,
BodyPart: exercisePart,
Level: exerciseLevel,
Image: thisRef
})
.then(function(){
console.log("Data entered successfully!");
})
.catch(function(error){
console.error("Error!", error);
});
}
You probably just want to save the full path of the reference, with thisRef.fullPath, as this is a simple string and not a full object.
To later translate that to an object that you could read, you'd do something like:
firebase.storage().ref().child(fullPath)
This obviously assumes the bucket hasn't changed -- otherwise you'd need to store the bucket name as well.
See more details here: https://firebase.google.com/docs/storage/web/create-reference.

code for getting the url picture in storage and put in database of firebase

var selectedFile;
$("#file").on("change", function(event) {
selectedFile = event.target.files[0];
$("#uploadButton").show();
});
function uploadFile() {
// Create a root reference
var filename = selectedFile.name;
var storageRef = firebase.storage().ref('/dogImages/' + filename);
var uploadTask = storageRef.put(selectedFile);
// Register three observers:
// 1. 'state_changed' observer, called any time the state changes
// 2. Error observer, called on failure
// 3. Completion observer, called on successful completion
uploadTask.on('state_changed', function(snapshot){
// Observe state change events such as progress, pause, and resume
// See below for more detail
}, function(error) {
// Handle unsuccessful uploads
}, function() {
// Handle successful uploads on complete
// For instance, get the download URL: https://firebasestorage.googleapis.com/...
var postKey = firebase.database().ref('Posts').push().key;
var downloadURL = uploadTask.snapshot.downloadURL;
var postData = {
url: downloadURL,
caption: $("#imageCaption").val()
};
var updatess = {};
updatess ['Posts' + postKey] = postData;
return firebase.database().ref().update(updatess);
});
}
The Error is Uncaught (in promise) Error: Reference.update failed: First argument contains undefined in property 'Posts-LRyHOS3r8-VP-7WMsCS.url' and it doesnt store in database of firebase. this is my code
The error message is quite explicit: downloadURL seems to be null. If you search for recent questions about this, you'll see that the download URL is now retrieved asynchronously by calling getDownloadURL().
So something like:
uploadTask.on('state_changed', function(snapshot){
// Observe state change events such as progress, pause, and resume
// See below for more detail
}, function(error) {
// Handle unsuccessful uploads
}, function() {
var postKey = firebase.database().ref('Posts').push().key;
var downloadURL = uploadTask.snapshot.downloadURL;
return storageRef.getDownloadURL().toPromise().then(downloadUrl => {
var postData = {
url: downloadUrl,
caption: $("#imageCaption").val()
};
var updatess = {};
updatess ['Posts' + postKey] = postData;
return firebase.database().ref().update(updatess);
});
});
Also see:
the Firebase documentation sample on uploads
the Firebase documentation on downloading files by URL
How do i get download URL once upload is done on firebase storage
Firebase get Download URL after successful image upload to firebase storage
I can't get image downloadUrl from Firebase Storage (Angular/Ionic)

Retrieve information from firebase doesn't work, key is not a function

I tried to solve it like this:
How to pull out data from firebase into html page - Stackoverflow
But I couldn't get it to work.
My html looks where I'll put the information from Firebase looks this in javascript:
var createTable = "<table><thead><tr id='keysRow'></tr></thead>";
var endHead = "<tbody><tr id='valuesRow'></tr></tbody></table>";
//More code that's connecting to each other and displays it in a div.
//F12 is showing me that this works.
Firebase.js:
var firebase = require('firebase');
firebase.initializeApp(config);
var v = firebase.database();
var users = firebase.database().ref("users");
users.orderByKey().once('child_added', function(snapshot){
snapshot.forEach(function(childsnapshot){
var key = childsnapshot.key(); <---------error
var data = childsnapshot.val();
$('#keysRow').append('<th>' + key + '</th>');
$('#valuesRow').append('<td>' + data + '</td>');
});
});
config is just the link to the firebase. I have no problem using the config to write in the firebase.
The error is telling me: "childsnapshot.key is not a function"
Also my firebase has 10 different values I need to get.
Change this:
var key = childsnapshot.key();
to this:
var key = childsnapshot.key;
check this link to see what has changed in Firebase 3.x: https://firebase.google.com/support/guides/firebase-web

Categories

Resources