How to upload an image using HTML and JavaScript in firebase ? - GeeksforGeeks

02 Nov, 2021
Firebase is a product of Google which helps developers to build, manage, and grow their apps easily. It helps developers to build their apps faster and in a more secure way. No programming is required on the firebase side which makes it easy to use its features more efficiently. It provides cloud storage. It uses NoSQL for the storage of data.
Here, We are going to learn How we can upload images using HTML and JavaScript in firebase. While working with the database we may require to upload an image file also.
Step By Step Implementation
Step 1: If you are new to firebase then please refer to this.
Activate Firebase Storage:
Click on the Storage button on the left and click on Get Started.
After that this box will pop up. Click on Next.
Then click on Done.
Step 2: Here we’re going to write the Html and JavaScript Code to connect Html Code with Firebase Database.
HTML
<!DOCTYPE html><html lang="en"> <head>    <meta charset="UTF-8">    <title>Collecting Data</title>    <link rel="stylesheet"          href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"          integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"          crossorigin="anonymous"> </head> <body class="container"      style="margin-top: 50px;             width: 50% height:auto; ">     <h2 class="text-primary"        style="margin-left: 15px; margin-bottom: 10px">              Hey There,Here we are going to upload    </h2>    <form class="container" id="contactForm">        <div class="card">            <div class="card-body">                 <div class="form-group"                     style="margin-left: 15px;                            margin-top: 10px;                            display:none;>    <label for=" exampleFormControlSelect1 ">Select Type</label>    <select class="form-control " id="types ">      <option>1</option>    </select>  </div> <br>    Document Upload:    <br>    <!-- click here to choose file -->    <input type="file " name="files[] " id="files ">    <!-- click here to upload file -->    <input type="hidden "           name="url "           id="url ">              <button type="button " onclick="uploadimage() ">               Upload Image            </button>           <br><br>  </div></div> <button type="submit "        class="btn btn-primary "        style="margin-left: 15px; margin-top: 10px; display:none; ">                Submit  </button> </form></body><script src="https://www.gstatic.com/firebasejs/3.7.4/firebase.js "></script><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js "></script> <link type="text/css " rel="stylesheet " href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css " /> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js "></script> <script>      // adding firebase data   var firebaseConfig = {    apiKey: "*********************- ",    authDomain: "-********************* ",    databaseURL: "********************* ",    projectId: "********************* ",    storageBucket: "********************* ",    messagingSenderId: "********************* ",    appId: "********************* "  };  firebase.initializeApp(firebaseConfig);  var messagesRef = firebase.database().ref('Checking');  document.getElementById(     'contactForm').addEventListener('submit', submitForm); //uploading file in storage  function uploadimage(){     var type = getInputVal('types');  var storage = firebase.storage();  var file=document.getElementById("files ").files[0];  var storageref=storage.ref();  var thisref=storageref.child(type).child(file.name).put(file);  thisref.on('state_changed',function(snapshot) {    }, function(error) {   }, function() {  // Uploaded completed successfully, now we can get the download URL  thisref.snapshot.ref.getDownloadURL().then(function(downloadURL) {    //getting url of image    document.getElementById("url ").value=downloadURL;    alert('uploaded successfully');    saveMessage(downloadURL);   });  });   // Get values  var url = getInputVal('url');  // Save message  // saveMessage(url);}function getInputVal(id){    document.getElementById('contactForm').reset(); }  // Function to get get form valuesfunction getInputVal(id){  return document.getElementById(id).value;} // Save message to firebase databasefunction saveMessage(url){  var newMessageRef = messagesRef.push();  newMessageRef.set({   imageurl:url,  });}</script></html>
After you have written the code you can run it using the below command in the terminal
python manage.py runserver 
Here, We will see the following screen after running it on any web browser.
After we select an image using choose file button we can choose any file, and then we will click on upload Image button to upload the image in firebase
In the Real-time database, we can see the image is uploaded successfully.
surinderdawra388
varshagumber28
Firebase
JavaScript-Questions
Technical Scripter 2020
JavaScript
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript