how to upload files to firebase cloud storage using javascript

04/04/2020    By: christoper unum





Firebase Storage is a cloud-based storage that can be used to store files. It is free to use up to 5GB, So exceeding this limit will require an upgrade. In this tutorial, we will be creating a web-based file uploader that lets you upload multiple files to Firebase Storage without using any backend programming language.

HTML

The first thing we need is a file input that will aid in selecting files and also we need a progress bar that will display the progress of our upload.

 Upload Files<br />
<input type="file" id="files" multiple /><br /><br />
<button id="send">Upload</button>
<p id="uploading"></p>
<progress value="0" max="100" id="progress"

To keep things simple, we won't be adding styles to our code. So our webpage looks like this now.

Upload Files


Creating A Project On Firebase

Before we can start uploading files to our storage, we need to get the firebase initialization code that connects your app to firebase. To get this code, you need to create a project on firebase. I have created a short video that guides you on how to create a project and initialize your storage bucket at console.firebase.google.com.

Add Firebase To Project

After creating your project, you should be able to obtain your firebase initialization code

 <!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.13.1/firebase-app.js"></script>

<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->

<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIzaSyCd_rU4ft1CCdYZJCAjM8OyAVVfZ8I14LQ",
authDomain: "file-upload-deae7.firebaseapp.com",
databaseURL: "https://file-upload-deae7.firebaseio.com",
projectId: "file-upload-deae7",
storageBucket: "file-upload-deae7.appspot.com",
messagingSenderId: "772980880174",
appId: "1:772980880174:web:273969e0f628410853c0bf"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
</script>

we also have to import our firebase storage SDK by adding this link as well.

 <script src="https://www.gstatic.com/firebasejs/7.13.1/firebase-storage.js"></script>       

Now we can add Javascript code that aids in transferring files to our Firebase Cloud Storage. If you added Firebase correctly to your app, your app should look something like this

 <!DOCTYPE html>
<html>
<head>
<title>Firebase File Upload</title>

<meta
name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1"
/>
</head>
<body>

<div>
Upload Files<br />
<input type="file" id="files" /><br /><br />
<button>Upload</button>
</div>

<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.13.1/firebase-app.js"></script>

<!-- TODO: Add SDKs for Firebase products that you want to use -->
<script src="https://www.gstatic.com/firebasejs/7.5.0/firebase-storage.js"></script>

<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIzaSyCd_rU4ft1CCdYZJCAjM8OyAVVfZ8I14LQ",
authDomain: "file-upload-deae7.firebaseapp.com",
databaseURL: "https://file-upload-deae7.firebaseio.com",
projectId: "file-upload-deae7",
storageBucket: "file-upload-deae7.appspot.com",
messagingSenderId: "772980880174",
appId: "1:772980880174:web:273969e0f628410853c0bf"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
</script>
</body>
</html>

Uploading Files To Firebase Storage

Uploading files to Firebase Cloud Storage is pretty straight forward. The first thing we have to do is to get the uploaded files data and store them in an array. We can achieve this by adding an onChange listener to the file input.

 <script>
var files = [];
document.getElementById("files").addEventListener("change", function(e) {
files = e.target.files;
});
</script>

Now to upload the stored files, we have to add a click listener on the button which takes the files and syncs them to your Firebase Cloud Storage.

 <script>
document.getElementById("send").addEventListener("click", function() {
//checks if files are selected
if (files.length != 0) {

//Loops through all the selected files
for (let i = 0; i < files.length; i++) {

//create a storage reference
var storage = firebase.storage().ref(files[i].name);

//upload file
var upload = storage.put(files[i]);

//update progress bar
upload.on(
"state_changed",
function progress(snapshot) {
var percentage =
(snapshot.bytesTransferred / snapshot.totalBytes) * 100;
document.getElementById("progress").value = percentage;
},

function error() {
alert("error uploading file");
},

function complete() {
document.getElementById(
"uploading"
).innerHTML += `${files[i].name} upoaded <br />`;
}
);
}
} else {
alert("No file chosen");
}
});
</script>

Reading From Firebase Cloud Storage

Reading from Firbase Cloud Storage is also pretty straight forward. We have to create a Firebase Storage reference and use it obtain the url of the file we want.

 <script>
function getFileUrl(filename) {
//create a storage reference
var storage = firebase.storage().ref(filename);

//get file url
storage
.getDownloadURL()
.then(function(url) {
console.log(url);
})
.catch(function(error) {
console.log("error encountered");
});
}
</script>

The Complete Html Document

This is the complete source code of this tutorial.

 <!DOCTYPE html>
<html>
<head>
<title>Firebase File Upload</title>

<meta
name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1"
/>
</head>
<body>
<div>
Upload Files<br />
<input type="file" id="files" multiple /><br /><br />
<button id="send">Upload</button>
<p id="uploading"></p>
<progress value="0" max="100" id="progress"></progress>
</div>

<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.13.1/firebase-app.js"></script>

<!-- TODO: Add SDKs for Firebase products that you want to use -->
<script src="https://www.gstatic.com/firebasejs/7.13.1/firebase-storage.js"></script>

<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIzaSyCd_rU4ft1CCdYZJCAjM8OyAVVfZ8I14LQ",
authDomain: "file-upload-deae7.firebaseapp.com",
databaseURL: "https://file-upload-deae7.firebaseio.com",
projectId: "file-upload-deae7",
storageBucket: "file-upload-deae7.appspot.com",
messagingSenderId: "772980880174",
appId: "1:772980880174:web:273969e0f628410853c0bf"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
</script>

<script>
var files = [];
document.getElementById("files").addEventListener("change", function(e) {
files = e.target.files;
for (let i = 0; i < files.length; i++) {
console.log(files[i]);
}
});

document.getElementById("send").addEventListener("click", function() {
//checks if files are selected
if (files.length != 0) {
//Loops through all the selected files
for (let i = 0; i < files.length; i++) {
//create a storage reference
var storage = firebase.storage().ref(files[i].name);

//upload file
var upload = storage.put(files[i]);

//update progress bar
upload.on(
"state_changed",
function progress(snapshot) {
var percentage =
(snapshot.bytesTransferred / snapshot.totalBytes) * 100;
document.getElementById("progress").value = percentage;
},

function error() {
alert("error uploading file");
},

function complete() {
document.getElementById(
"uploading"
).innerHTML += `${files[i].name} upoaded <br />`;
}
);
}
} else {
alert("No file chosen");
}
});

function getFileUrl(filename) {
//create a storage reference
var storage = firebase.storage().ref(filename);

//get file url
storage
.getDownloadURL()
.then(function(url) {
console.log(url);
})
.catch(function(error) {
console.log("error encountered");
});
}
</script>
</body>
</html>

Firebase Rules

In a way to help secure your app, Firebase gives you the ability to set rules. You can find the complete documentation of the rules at firebase.google.com/docs/rules.

Conclusion

Firebase Storage is very easy to use and easy to access. You can upload your files to cloud without the help of any back-end programming language or Hosting. Hope you learnt a lot from this tutorial, I will be doing more tutorials on firebase soon.



Recent Posts

blog image
blog image
blog image

Our Newsletters