firebase storage file name change - javascript

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) {
...

Related

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'

Get Download Url after firebase's resize extension completed

This is what I am trying to achieve, implement the firebase's resize image extension, upload an image, then when the resize is completed, add that dowloadUrl's thumbs to a Cloud Firestore document. This question helps me, but still can not identify the thumbs and get the download URL, this is what am have been trying so far.
Note: I set my thumbnail to be at root/thumbs
const functions = require('firebase-functions');
const { Storage } = require('#google-cloud/storage');
const storage = new Storage();
exports.thumbsUrl = functions.storage.object().onFinalize(async object => {
const fileBucket = object.bucket;
const filePath = object.name;
const contentType = object.contentType;
if (fileBucket && filePath && contentType) {
console.log('Complete data');
if (!contentType.startsWith('thumbs/')) {
console.log('This is not a thumbnails');
return true;
}
console.log('This is a thumbnails');
} else {
console.log('Incomplete data');
return null;
}
});
Method 1 : Client Side
Don't change the access token when creating the thumbnail.
Edit the function from gcloud cloud function console
Go to the function code by clicking detailed usage stats
Then click on code
Edit the following lines
Redeploy the function again
// If the original image has a download token, add a
// new token to the image being resized #323
if (metadata.metadata.firebaseStorageDownloadTokens) {
// metadata.metadata.firebaseStorageDownloadTokens = uuidv4_1.uuid();
}
Fetch the uploaded image using getDownloadURLfunction
https://firebasestorage.googleapis.com/v0/b/<project_id>/o/<FolderName>%2F<Filename>.jpg?alt=media&token=xxxxxx-xxx-xxx-xxx-xxxxxxxxxxxxx
Because the access token will be similar
https://firebasestorage.googleapis.com/v0/b/<project_id>/o/<FolderName>%2Fthumbnails%2F<Filename>_300x300.jpg?alt=media&token=xxxxxx-xxx-xxx-xxx-xxxxxxxxxxxxx
Method 2: Server Side
Call this function after thumbnail is created
var storage = firebase.storage();
var pathReference = storage.ref('users/' + userId + '/avatar.jpg');
pathReference.getDownloadURL().then(function (url) {
$("#large-avatar").attr('src', url);
}).catch(function (error) {
// Handle any errors
});
you need to use filePath for checking the thumbs
if(filePath.startswith('thumbs/'){...}
contentType has the metadata of files like type of image and etc.
FilePath will have the full path.

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)

How to display image from firebase storage using 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);
});
});
})

How to save a copy of an image (located at a URL) to Firebase Storage (web) using Javascript?

I'm trying to create a copy of an image (which is located at a url), and save it to Firebase's storage facility. I want to store the actual image file and not just the url. If I understand correctly, I first need to convert the image at the url to a blob or file and then upload the data to the Firebase storage.
This is my current attempt with Javascript:
function savePicture(){
var url = ["http://carltonvet.com.au/sites/default/files/styles/large/public/images/article/cats.jpg"];
var blobpic = new Blob(url, {type: 'file'});
console.log(blobpic);
var user = firebase.auth().currentUser;
if (user != null) {
var userid = user.uid;
var ref = firebase.storage().ref(userid + "profilePhoto");
ref.put(blobpic).then(function(snapshot) {
console.log('Picture is uploaded!');
console.log(snapshot);
var filePath = snapshot.metadata.fullPath;
document.getElementById('picTestAddress').innerHTML = ""+filePath;
document.getElementById('picTestImage').src = ""+filePath;
});
}else{
console.log("Something went wrong, user is null.");
}
}
I have two HTML tags like this:
<div id="picTestAddress"></div>
<img id="picTestImage" />
I'm pretty sure this is only saving the url and not the physical image.
The "picTestAddress" gets filled in with "qAjnfi387DHhd389D9j3r/profilePhoto", and the console shows the following error for "picTestImage": GET file:///android_asset/www/qAjnfi387DHhd389D9j3r/profilePhoto net::ERR_FILE_NOT_FOUND
I'm using Firebase for Web and Cordova. And I'm testing the app on my android phone.
I understand that the error is because it's looking for the image on my phone's local file system. This makes sense to me, so I thought I could fix this by appending my app's address to the beginning of the filePath (eg: document.getElementById('picTestImage').src = "https://firebasestorage.googleapis.com/v0/b/MY_APP.appspot.com/o/"+filePath;).
To find the correct path, I navigated to the file's location in the Firebase console and copied the "Download url" address - but when I checked this (by entering it into my web browser) it loaded a white page which contained one line of text, which was the original url: "http://carltonvet.com.au/sites/default/files/styles/large/public/images/article/cats.jpg"
So now I think I've just saved the url to the storage instead of the actual image file.
I've been following the Firebase docs, and I think I have the uploading part working correctly, but I think I'm failing when it comes to converting the url to the blob/file with Javascript.
I've looked through some other questions, such as this one: How to store and view images on firebase? and was going to follow the example here: https://github.com/firebase/firepano but it says that it's now a legacy example and I can't seem to find an updated version in Firebase's samples section.
Any advice or help with how to do this would be really appreciated.
Thank you in advance!
Looks good, though I'd also consider a promisified version:
function getBlob(url) {
return new Promise(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(event){
var blob = xhr.response;
resolve(blob);
};
xhr.onerror = reject();
xhr.open('GET', url);
xhr.send();
}
}
function storageURLForPhoto(oldURL, newName) {
getBlob(oldURL)
.then(function(blob) {
var picRef = firebase.storage().ref().child(newName);
return picRef.put(blob)
})
.then(function(snapshot) {
return snapshot.downloadURL;
});
.catch(function() {
// handle any errors
})
}
Little easier to reason about :)
The following works:
function savePhoto(){
var url = "http://www.planetware.com/photos-large/F/france-paris-eiffel-tower.jpg";
// First, download the file:
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(event) {
var blob = xhr.response;
// Get the current user:
var user = firebase.auth().currentUser;
if (user != null) {
var userid = user.uid;
// Define where to store the picture:
var picRef = firebase.storage().ref(userid + "/profilePhoto");
// Store the picture:
picRef.put(blob).then(function(snapshot) {
console.log('Picture uploaded!');
// Now get image from storage and display in div...
picRef.getDownloadURL().then(function(pic) {
var userspic = pic;
document.getElementById('picTestImage').src = userspic;
}).catch(function(error) {
console.log("There was an error: "+error);
});
});
}else{
console.log("We weren't able to confirm there is a current user, something went wrong.");
}
};
xhr.open('GET', url);
xhr.send();
}

Categories

Resources