Uploading an image with data to Google Firebase

<Blake†Codez />
7 min readSep 7, 2020

--

Image by Caspar Camille Rubin

Hey everyone! Recently I have been working on a project for a company locally here in Redding, Ca while being a Bethel School of Technology student that has called me to create a specific functionality for this application: Uploading a User’s form data with an image attached to it and storing that data on a cloud server.

In this article I will be using Google Firebase as my cloud server to host data and store files. I will be using a simple HTML form for the user to enter the data, and then I will use JavaScript and Firebase SDK’s to upload the data as an On Click function for the Form.

Let’s start by creating a basic Google Firebase Project:

Create Google Firebase Project
  1. Click on Add Project +
Name the Project

2. Name the Project, click continue

Disable Analytics

3. I chose to disable analytics, click Create Project

Open Project

4. Open Project — click continue

5. Next we are going to put our Firebase SDK into our application. Click on the < /> symbol to do this.

Click on the < /> Symbol.

6. You will be asked to name the application. Enter a name that works for you, I chose form-data-app.

7. Copy and paste the following into your application. I created an index.html and app.js file in my VSCode and inserted this into both files. I also created the form and styled it. Code shown below:

Copy and paste the text given to a .js file
Index.html
App.js

Here is the styling for the form. Basic here we are only implementing functionality for this tutorial! :)

Style for form

Should look like this when running Live Server or Default Browser in VSCode:

Running on Live Server

I setup the Form with basic data to show what happens when pushing to Cloud and I also put in a File Input to grab an image or file from the Form and upload it.

We are going to be using 2 Products from Firebase to host our Data. Firebase Storage and Cloud Firestore. We will select those from the menu on the left, and create them.

Let’s Setup Storage 1st. Here we will navigate to the Storage link in the Menu on the Upper Left of the screen in the Firebase Console. We will click on it, then click get Started. Click next and Click done. We will then Edit the Rules.

Navigate to Storage on Menu — Click Get started
Click Next
Click Done

Next we will setup the Rules for accessing this storage. I am going to choose to bypass any security measures at the moment by writing the following code to the rules:

Setup Rules
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth == null;
}
}
}

Note this is not the best advice because anyone with your Firebase information could potentially read/write to this folder, but we are just using this for an example to quickly upload files. Setup your authorization later if you choose to ever implement to an actual application!

Now that Storage is locked in, let’s include Cloud Firestore in this application. Navigate to Cloud Firestore in the Menu on the top left, and click. Then click Create Database.

Create Database

Let’s setup the rules and timezone for this app. We will be using Test Mode, which is basically allowing anyone to read/write to this without authorization, so again this is only for this example atm.

Start in Test Mode
Click Enable

Next let’s create a collection. This is where we can reference and store the data. We will be using the following fields: name, email, message, image_url, and timestamp to keep track of date. The image_url we will use to reference where the image is located in our Storage.

Start a Collection
Create the following fields
Finished creating collection

These fields will be our basic model. Note we don’t have to model off this data. We can add any type of data we want, and the next document will have the fields we want to include, so it doesn’t force you to have specific fields included in your data. This is just an example of how our application will run though.

Now that we have everything setup we can begin coding our application using Firebase.

To Start let’s grab some SDKs that we need to allow us to access Storage and Firestore. I am also including a library called UUID because each time the User submits this form, I want to generate a unique ID to this set of data. I will use this to track the image as well, and we can reference it whenever we choose to grab the unique set of data.

Adding SDKS and UUID Library
<script src="https://www.gstatic.com/firebasejs/7.19.1/firebase-app.js"></script><!-- TODO: Add SDKs for Firebase products that you want to usehttps://firebase.google.com/docs/web/setup#available-libraries --><script src="https://www.gstatic.com/firebasejs/7.19.1/firebase-firestore.js"></script><script src="https://www.gstatic.com/firebasejs/7.19.1/firebase-storage.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/node-uuid/1.4.8/uuid.min.js"></script>

I am going to navigate back to app.js and start declaring some functions. I created 2 functions, 1 onSubmit(event) and 1 chooseFile(event). This chooseFile function I will use to grab the file object when I need it to upload it to the Storage. This will be an onchange function. onSubmit will grab all of the data from the form I created, and upload the data to Firestore and Storage.

Create 2 functions chooseFile() and onSubmit()
let file = {};const chooseFile = (e) => {  file = e.target.files[0];}const onSubmit = (event) => {  event.preventDefault();}
add onchange event to include chooseFile() function

Now let’s start coding our onSubmit() function!

1st I declared the variables I needed and grabbed the data from the document. The imageUrl is the location on my Storage where I am going to send my file.

Declare FORM DATA variables
Write to Firestore the data
const onSubmit = (event) => {  event.preventDefault();  let uniqueID = uuid.v4();  let image = file;  let imageUrl = `/images/${uniqueID}/${image.name}`; // image.name = name of image uploaded  const INPUT_NAME = document.getElementById('inputName').value;  const INPUT_EMAIL = document.getElementById('inputEmail').value;  const TEXTAREA_MESSAGE =   document.getElementById('inputMessage').value;const FORM_DATA = {  name: INPUT_NAME,  email: INPUT_EMAIL,  message: TEXTAREA_MESSAGE,  imageUrl: imageUrl, // where I am storing my Image  timestamp: firebase.firestore.FieldValue.serverTimestamp()  //Time   Stamp the Data}firebase  .firestore() // reference cloud firestore  .collection('form-data') //reference collection  .add({    FORM_DATA   })console.log("Uploading Data to Firestore: \n", FORM_DATA)}

Above, I am calling firebase to make a call to the firestore() sdk, reference the collection i mage ‘form-data’ and add the following FORM_DATA object to the collection as a document.

We should see this upload all of the data straight to Cloud Firestore:

Submit some Data, check console
Check Firestore

Boom! We uploaded some data to the Cloud Firestore!

What about the image? Let’s write some more functionality to the onSubmit() function that allows for this:

Write image to Storage
var storageRef = firebase.storage().ref(imageUrl); // References where we will store imagestorageRef.put(image)  .then(function(snapshot){  console.log(snapshot);  console.log('Uploading Image to Storage: \n', imageUrl)})

Now let’s submit the form again and check our Storage and Firestore:

Resubmit Form
Check Firestore
Check Storage

Look! We successfully uploaded our image to Storage. Cool thing is in the form-data collection we have a reference to where this file is located at all times now! So we can grab the download data from Firebase anytime we want to use this image in the future for our application!

Let’s write some code to get the data we need to render it to a Front End of this application! In my next article I will build a React.js application that will render this data on the Front End.

Thanks for reading my article! Spread the love! Keep collaborating with others and help other students learn coding skills. We are all in this together.

Bless!

--

--

<Blake†Codez />
<Blake†Codez />

Written by <Blake†Codez />

I’m a Software Engineering student in Redding, Ca. Love all things Computer Science related, love for journalism, Jesus Christ, and team collaboration projects.

No responses yet