Uploading an image with data to Google Firebase
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:
- Click on Add Project +
2. Name the Project, click continue
3. I chose to disable analytics, click Create 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.
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:
Here is the styling for the form. Basic here we are only implementing functionality for this tutorial! :)
Should look like this when running Live Server or Default Browser in VSCode:
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.
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:
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.
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.
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.
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.
<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.
let file = {};const chooseFile = (e) => { file = e.target.files[0];}const onSubmit = (event) => { event.preventDefault();}
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.
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:
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:
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:
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!