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'
Related
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) {
...
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.
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.
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)
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);
});
});
})