How to display image from firebase storage using javascript? - javascript

I tried to upload an image to firebase storage and retrieve the image from firebase storage. But, the "retrieve" case is not working:
// image upload
var storageRef = firebase.storage().ref('profilePicturesOfAbmin/original/'+file.name);
storageRef.put(file);
function error(err) {
console.log("error",err);
}
// retrieve image from firebase storage
var storageRef = firebase.storage().ref();
var spaceRef = storageRef.child('profilePicturesOfAbmin/original/'+file.name);
storageRef.child('profilePicturesOfAbmin/original/'+file.name).getDownloadURL().then(function(url) {
console.log("bsbdsbsdbd");
var test = url;
alert("hfdghjghj",url);
}).catch(function(error) { });

So with seeing your error message the idea is todo
StorageRef.put(file, function(){
// Now do the download
})
Or have a handler that waits till the file is uploaded

You might want to try something like this...
var storageRef = firebase.storage().ref(filePath);
function uploadImage(event){
var file = event.target.files[0];
return storageRef.put(file).then(function(snapshot) {
// put the file now do something...
var fullPath = snapshot.metadata.fullPath;
console.log(fullPath);
}).catch(function(error){
console.log("error uploading "+error);
});
}
function retrieveImage(imageUri, imgElement){
if (imageUri.startsWith('gs://')) {
storageRef.refFromURL(imageUri).getMetadata().then(function(metadata) {
imgElement.src = metadata.downloadURLs[0];
console.log("URL is "+metadata.downloadURLs[0]);
}).catch(function(error){
console.log("error downloading "+error);
});
}
}
This will use Promise's to carry out actions once the file has been uploaded successfully.
It will also log to the console when error's occur.

var storageRef = firebase.storage().ref('profilePicturesOfAbmin/original/')
storageRef.listAll().then(res => {
//for folders
res.perfixes.forEach(folder => {
console.log(folder);
});
// for files NAME and URL
res.items.forEach(item => {
// console.log( item.name );
item.getDownloadURL().then(function (url) {
console.log(url);
});
});
})

Related

How to get file name from download link in firebase storage(Javascript, React)?

I've being trying to get files name from Firebase storage.
Right now I got a download link and trying to get name from it.
const showPhoto = () => {
var eventDOM = event.target;
var src = eventDOM.getAttribute('src');
setpickImage(src);
console.log(src);
// src = "https://firebasestorage.googleapis.com/v0/b....."
}
I need file name to delete file from storage.
If you want to map a download URL back to a file name, use the refFromURL method.
Also see the documentation on creating a reference from a download URL, which contains this example:
var httpsReference = storage.refFromURL('https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg');
From that Reference you can then get other properties like the file's name.
let fileName = httpsReference.name;
To get the file name and url or download link of the videos or files from the firebase storage you can use these two functions in javascript and react
// function to fetch videos / files from firebase storage
const fetchVideos = async() => {
const storageRef = firebase.storage().ref("your storage folder name");
const videos = [];
await storageRef
.listAll()
.then(async function(result) {
result.items.forEach(async function(videoRef) {
// getting the name of the file
const videoName = videoRef.name;
// getting the url of the file -> calling another function for this
const videoUrl = await getVideoUrl(videoRef);
// creating the object with name and url
const videoObj = {
videoName,
videoUrl,
};
console.log("video obj", videoObj);
videos.push(videoObj);
});
})
.catch(function(error) {
// Handle any errors
return [];
});
}
// function to get download url
const getVideoUrl = (imageRef) => {
const videoLink = imageRef
.getDownloadURL()
.then(function(videoUrl) {
console.log("videoUrl", videoUrl);
return videoUrl;
})
.catch(function(error) {
// Handle any errors
return "";
});
return videoLink;
};

How to delete a file from firebase storage using JavaScript

Hi I want to delete a file from firebase storage. My storage hierarchy is simple and looks like this.
I searched for the method on how to delete file from firebase storage i found this.
function deletingFile(fileName, file, b ) {
// Create a reference to the file to delete
// const storageRef = firebase.storage().ref();
var desertRef = firebase.storage().ref().child(fileName);
// Delete the file
desertRef.delete().then(function () {
alert('file deleted successfully');
var delImg = firebase.database().ref('students').child(abc).once('value')
.then(function (data) {
data.val().file.set() = {};
})
$(b).parents('tr').remove();
// File deleted successfully
}).catch(function (error) {
alert(error)
// Uh-oh, an error occurred!
});
} // function deleting file ended here
Now when I am calling this function the following error is obtained, I am unable to resolve what is wrong here. fileName == 'DailyEase Color Theme.txt'

firebase storage file name change

I am a newbie to firebase and Javascript.
How do I change the file name to user's uid and save it to storage?
And I want to upload a file after successful registration. Should I write a function in createUserWithEmailAndPassword or onAuthStateChanged?
function handleFileSelect(evt) {
evt.stopPropagation();
evt.preventDefault();
var file = evt.target.files[0];
var metadata = {
'contentType': file.type
};
var storage_ref = storage.ref();
storage_ref.child('userImages/' + user.uid).put(file, metadata).then(function(snapshot) {
snapshot.ref.getDownloadURL().then(function(url) {
console.log('File available at', url);
profile_url = url;
});
}).catch(function(error) {
console.error('Upload failed:', error);
});
} // handleFileSelect
document.getElementById('input_img').addEventListener('change',handleFileSelect, false);
You can't change the file name directly. But there is an indirect way to do that, check this question
You want User's UID as file name but you won't get that in createUserWithEmailAndPassword so you need to add that logic into onAuthStateChanged method. But onAuthStateChanged get called every time whenever users login so you need to build some kind of logic to execute your file upload method only first time when user log in.
To take an action in response to the user account being created, you can use then.
So something like:
function handleFileSelect(evt) {
evt.stopPropagation();
evt.preventDefault();
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
}.then(function(credential) {
var user = credential.user
var file = evt.target.files[0];
var metadata = {
'contentType': file.type
};
var storage_ref = storage.ref();
storage_ref.child('userImages/' + user.uid).put(file, metadata).then(function(snapshot) {
snapshot.ref.getDownloadURL().then(function(url) {
...

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)

Upload a photo to Firebase Storage with Image URI

I am currently attempting to upload a photo to my Firebase app's storage in my Apache Cordova app. I currently get the photo's URI with the following code:
function getPhotoFromAlbum() {
navigator.camera.getPicture(onPhotoURISuccess, onFail, {
quality: 50,
sourceType: navigator.camera.PictureSourceType.SAVEDPHOTOALBUM,
destinationType: navigator.camera.DestinationType.FILE_URI
});
}
function onPhotoURISuccess(imageURI) {
var image = document.getElementById('image');
image.style.display = 'block';
image.src = imageURI;
getFileEntry(imageURI);
}
And then am attempting to convert the image into a file and push it to my Firebase storage with the following function:
function getFileEntry(imgUri) {
window.resolveLocalFileSystemURL(imgUri, function success(fileEntry) {
console.log("got file: " + fileEntry.fullPath);
var filename = "test.jpg";
var storageRef = firebase.storage().ref('/images/' + filename);
var uploadTask = storageRef.put(fileEntry);
}, function () {
// If don't get the FileEntry (which may happen when testing
// on some emulators), copy to a new FileEntry.
createNewFileEntry(imgUri);
});
}
I have both the file and the camera cordova plugins installed, the only errors I get when I attempt to do this is
Error in Success callbackId: File1733312835 : [object Object]
Which is just an error message from cordova.js
I also know I have my Firebase storage set up correctly because I have tested it through an emulator by adding a file input and successfully uploading whatever file the user added, to the Firebase storage.
Is it possible to upload a file to Firebase storage using this method of converting an image to a file through its URI, and then uploading it? If so, what is the correct way to do so / what is wrong with the way i'm doing it?
I was able to accomplish uploading an image by using a data url. Below is my code:
var filename = "test.jpg";
var storageRef = firebase.storage().ref('/images/' + filename);
var message = 'data:image/jpg;base64,' + imageUri;
storageRef.putString(message, 'data_url').then(function (snapshot) {
console.log('Uploaded a data_url string!');
});
Is it possible to upload a file to Firebase storage using this method of converting an image to a file through its URI, and then uploading it? If so, what is the correct way to do so / what is wrong with the way i'm doing it?
Yes it is possible to upload a file on firebase through its URI. However you have to follow the correct way.
1. You have to store the data in firebase after file reading operation is completed.you can use FileReader.onloadend for this.
2. By using a data_url you can store to firebase.
Here is the snippet for more clarity:
function getFileEntry(imgUri) {
window.resolveLocalFileSystemURL(imgUri, function onSuccess(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function() {
filename = "test.jpg";
var storageRef = firebase.storage().ref('/images/' + filename);
var data = 'data:image/jpg;base64,' + imgUri;
storageRef.putString(data, 'data_url').then(function (snapshot) {
console.log('Image is uploaded by base64 format...');
});
};
reader.readAsArrayBuffer(file);
});
},
function onError(err) {
console.log(err);
createNewFileEntry(imgUri);
});
}

Categories

Resources