#FIREBASE TIPS
1. Upload file
upload.html
<script>
firebase.initializeApp(config);
firebase.auth().signInWithEmailAndPassword('xxx@xxx.com', 'xxx').catch((error) => {
console.log('code:' + error.code + 'message' + error.message);
});
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
console.log('login success');
} else { }
});
var storage = firebase.storage();
function upload() {
var file = document.getElementById('loadFile').files[0];
console.log('/images/' + file.name);
var storageRef = storage.ref('/images/' + file.name);
storageRef.put(file).then(function (snapshot) {
console.log('Uploaded a blob or file!');
});
}
</script>
<body>
<input type="file" id="loadFile" name="loadFile" />
<input type="button" id="button" name="button" value="upload" onclick="upload()" />
</body>
storage.rule
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
2. Download file
<script>
firebase.initializeApp(config);
firebase.auth().signInWithEmailAndPassword('xxx@xxx.com', 'xxx').catch((error) => {
console.log('code:' + error.code + 'message' + error.message);
});
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
console.log('login success');
} else { }
});
var storage = firebase.storage();
storageRef = storage.ref('');
storageRef.child('images/logo.png').getDownloadURL().then(function (url) {
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function (event) {
var blob = xhr.response;
};
xhr.open('GET', url);
xhr.send();
// Or inserted into an <img> element:
var img = document.getElementById('photo1');
img.src = url;
}).catch(function (error) {
// Handle any errors
});
</script>
<body>
<img id="photo1">
</body>
3. Delete file
<script>
firebase.initializeApp(config);
firebase.auth().signInWithEmailAndPassword('coffeeandcode.tokyo@gmail.com', 'coffee').catch((error) => {
console.log('code:' + error.code + 'message' + error.message);
});
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
console.log('login success');
} else { }
});
var storage = firebase.storage();
storageRef = storage.ref('');
storageRef.child('images/logo.png').delete().then(() => {
console.log('delete success');
}).catch((error) => {
console.log('delete error');
});
</script>