Created
August 15, 2019 18:06
-
-
Save sawaYch/f538d10d09ccf84cbff07e93a0b6cd0d to your computer and use it in GitHub Desktop.
Firebase storage listAll() example.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Load single image | |
// replace images/photo6244288433388366130.jpg with your image path | |
// You can find it on the firebase storage console | |
var imgRef = firebase.storage().ref().child('images/photo6244288433388366130.jpg'); | |
imgRef.getDownloadURL().then(function(url){ | |
var img = document.getElementById('img1'); | |
img.src = url; | |
}).catch(function(error) { | |
// A full list of error codes is available at | |
// https://firebase.google.com/docs/storage/web/handle-errors | |
switch (error.code) { | |
case 'storage/object-not-found': | |
// File doesn't exist | |
console.log('file not exist'); | |
break; | |
case 'storage/unauthorized': | |
// User doesn't have permission to access the object | |
console.log('permission problems'); | |
break; | |
case 'storage/canceled': | |
// User canceled the upload | |
console.log('canceled'); | |
break; | |
case 'storage/unknown': | |
// Unknown error occurred, inspect the server response | |
console.log('unknown'); | |
break; | |
} | |
}); | |
// Load all images within folder | |
// (and create img elements) | |
// First of all you need to edit your security rules from ver.1 to ver.2 | |
rules_version = '2'; // Add this line | |
service firebase.storage { // Your rules here | |
match /b/{bucket}/o { | |
match /{allPaths=**} { | |
allow read; | |
allow write: if auth.uid == 'blablabla'; | |
} | |
} | |
} | |
// On your Web Apps | |
// index.html | |
<div id="img-area"></div> | |
// script.js | |
var img_index = 1; | |
var storageRef = firebase.storage().ref(); | |
var listRef = storageRef.child('images'); | |
listRef.listAll().then(function(result){ | |
console.log(result); | |
result.items.forEach(function(imgRef){ | |
imgRef.getDownloadURL().then(function(url){ | |
var img = $('<img />').attr({ | |
'id': 'poster'+img_index, | |
'src': url, | |
'alt': 'image', | |
'title': 'image', | |
'width': 250 | |
}).appendTo('#img-area'); | |
img_index++; | |
}); | |
}) | |
}).catch(function(error){ | |
console.log(error); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment