Hello Friends, today we are going to learn how to download & upload file to firebase storage using Javascript API. Cloud Storage is built for app developers who need to store and serve user-generated content, such as photos or videos. To use firebase cloud storage in our project we first need to setup project and app on firebase console and copy configuration. To setup project and create app for configuration kindly check this official link but I am also attaching some screenshots for help which I have taken while creating project and app.
Please note you can also list files of firebase cloud storage but you need to change firebase security rules and then this official guide link can help you listing files.
step-wise screenshots taken while creating project |
step-wise screenshots taken while creating app |
After creating project and app we need to replace firebaseConfig in init-firebase.js with the firebaseConfig got in step 3 while creating app and we also have to enable Anonymous in Sign-in method, which we can find under Authentication section.
init-firebase.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Your web app's Firebase configuration var firebaseConfig = { apiKey: "api-key", authDomain: "project-id.firebaseapp.com", databaseURL: "https://project-id.firebaseio.com", projectId: "project-id", storageBucket: "project-id.appspot.com", messagingSenderId: "sender-id", appId: "app-id", measurementId: "G-measurement-id", }; // Initialize Firebase firebase.initializeApp(firebaseConfig); |
Now here is the code goes
index.html
1 2 3 4 5 6 7 8 9 |
<html> <head> <title>Firebase Storage</title> </head> <body> <a href="upload.html">Upload</a><br/> <a href="download.html">Generate Download Link</a> </body> </html> |
upload.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
<!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Firebase Storage Upload File</title> </head> <body> <div> <h2 class="">Upload a file</h2> <div> <p>Select a file below. When it is uploaded, a link will be displayed to the uploaded file.</p> <h6>Choose File</h6> <input type="file" id="file" name="file"/> <h6>File URL:</h6> <span id="linkbox"></span> </div> </div> <!-- Import and configure the Firebase SDK --> <!-- These scripts are made available when the app is served or deployed on Firebase Hosting --> <!-- If you do not serve/host your project using Firebase Hosting see https://firebase.google.com/docs/web/setup --> <!-- The core Firebase JS SDK is always required and must be listed first --> <script src="https://www.gstatic.com/firebasejs/7.14.0/firebase-app.js"></script> <!-- TODO: Add SDKs for Firebase products that you want to use https://firebase.google.com/docs/web/setup#available-libraries --> <!-- Add Firebase products that you want to use --> <script src="https://www.gstatic.com/firebasejs/7.14.0/firebase-auth.js"></script> <script src="https://www.gstatic.com/firebasejs/7.14.0/firebase-storage.js"></script> <script src="init-firebase.js"></script> <script> var auth = firebase.auth(); var storageRef = firebase.storage().ref(); function handleFileSelect(evt) { evt.stopPropagation(); evt.preventDefault(); var file = evt.target.files[0]; var metadata = { 'contentType': file.type }; // Push to child path. // [START oncomplete] storageRef.child('images/' + file.name).put(file, metadata).then(function (snapshot) { console.log('Uploaded', snapshot.totalBytes, 'bytes.'); console.log('File metadata:', snapshot.metadata); // Let's get a download URL for the file. snapshot.ref.getDownloadURL().then(function (url) { console.log('File available at', url); // [START_EXCLUDE] document.getElementById('linkbox').innerHTML = '<a href="' + url + '">' + url + '</a>'; // [END_EXCLUDE] }); }).catch(function (error) { // [START onfailure] console.error('Upload failed:', error); // [END onfailure] }); // [END oncomplete] } window.onload = function () { document.getElementById('file').addEventListener('change', handleFileSelect, false); document.getElementById('file').disabled = true; auth.onAuthStateChanged(function (user) { if (user) { console.log('Anonymous user signed-in.', user); document.getElementById('file').disabled = false; } else { console.log('There was no anonymous session. Creating a new anonymous user.'); // Sign the user in anonymously since accessing Storage requires the user to be authorized. auth.signInAnonymously().catch(function (error) { if (error.code === 'auth/operation-not-allowed') { window.alert('Anonymous Sign-in failed. Please make sure that you have enabled anonymous ' + 'sign-in on your Firebase project.'); } }); } }); } </script> </body> </html> |
download.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
<html> <head>Firebase Storage Download File</head> <body> <div> <h2 class="">Download a file</h2> <div> <p>Enter file name in the below text box to generate download link</p> <h6>File Name</h6> <input type="text" id="file" name="file"/> <input type="button" value="Generate" onclick="generateDownloadLink()"/> <h6>File URL:</h6> <span id="linkbox"></span> </div> </div> <!-- The core Firebase JS SDK is always required and must be listed first --> <script src="https://www.gstatic.com/firebasejs/7.14.0/firebase-app.js"></script> <!-- Add Firebase products that you want to use --> <script src="https://www.gstatic.com/firebasejs/7.14.0/firebase-auth.js"></script> <script src="https://www.gstatic.com/firebasejs/7.14.0/firebase-storage.js"></script> <script src="init-firebase.js"></script> <script> var auth = firebase.auth(); var storageRef = firebase.storage().ref(); function generateDownloadLink() { var fileName = document.getElementById("file").value; storageRef.child("images/" + fileName).getDownloadURL().then(function (url) { document.getElementById('linkbox').innerHTML = '<a href="' + url + '">' + url + '</a>'; }).catch(function (error) { console.log(error); document.getElementById('linkbox').innerHTML = error.code; }); } window.onload = function () { auth.onAuthStateChanged(function (user) { if (user) { console.log('Anonymous user signed-in.', user); } else { console.log('There was no anonymous session. Creating a new anonymous user.'); // Sign the user in anonymously since accessing Storage requires the user to be authorized. auth.signInAnonymously().catch(function (error) { if (error.code === 'auth/operation-not-allowed') { window.alert('Anonymous Sign-in failed. Please make sure that you have enabled anonymous ' + 'sign-in on your Firebase project.'); } }); } }); } </script> </body> </html> |
Screenshots
Download Netbeans Project
Firebase Storage Netbeans Project
Thanks friends
Queries & Suggestions are welcome in comment
Please don’t forget to share if you find this helpful
Comments