Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save m3l1nd4/bdba205e625214598868cade2f6d144e to your computer and use it in GitHub Desktop.
Save m3l1nd4/bdba205e625214598868cade2f6d144e to your computer and use it in GitHub Desktop.
// Uploading picture
function uploadImageToFirebaseStorage(elementName, fileName, img, edit) {
// // Create a reference for the storage, the folder and the filename
const storageRef = firebase.storage().ref('products/' + fileName);
// Upload the file and metadata
const uploadTask = storageRef.putString(img, 'base64');
// 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(firebase.storage.TaskEvent.STATE_CHANGED,
function (snapshot) {
// Observe state change events such as progress, pause, and resume
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
elementName.innerHTML = 'Upload is ' + Math.trunc(progress) + '% done';
if (progress == 100) {
if (edit)
app.dialog.alert('Saved product details.', '');
else {
app.dialog.alert("Product added to the products list.", "");
app.methods.emptyNewProductForm();
document.getElementById("imageFile").src = "assets/pictures/camera.png";
elementName.innerHTML = "";
}
}
switch (snapshot.state) {
case firebase.storage.TaskState.PAUSED:
console.log('Upload is paused'); // or 'paused'
break;
case firebase.storage.TaskState.RUNNING:
console.log('Upload is running'); // or 'running'
break;
}
},
function (error) {
// Handle unsuccessful uploads
switch (error.code) {
case 'storage/unauthorized':
break;
case 'storage/canceled':
break;
case 'storage/unknown':
break;
case 'storage/invalid-format':
break;
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment