Firebase Record Path When Uploading to Storage

Firebase Storage is a swell way to store all the asset files for your projects in a single place.

You can store pretty much whatever files such as:

  • images,
  • videos,
  • audio,
  • documents, etc

You can too create folders to organize other files or folders.

Uploading files and downloading file URLs are super piece of cake and nosotros can hands protect them using Firebase Storage Security Rules, which is very similar to Cloud Firestore Security Rules.

Table of Contents

  • Setting Up Firebase Storage
  • Cull An Image
  • Upload An Image
  • Multiple Storage Buckets
  • Become An Image
  • Upload Multiple Files
  • Get All Images
  • Delete A File
  • Firebase Storage With Authentication Demo
    • Create A New Firebase Business relationship
    • Firebase Storage Construction & Security Rules
    • Upload Logged-In User's Profile Film
    • Get Logged-In User'south Contour Movie

Enable Firebase Storage

Enable Firebase Storage by clicking the Get Started push after logging into the Firebase account.

The default Cloud StorageSecurity Rule will be set to "just authenticated users tin can read and write data",

Click next.

And then, information technology gives us a warning saying that one time the Firebase Cloud Storage bucket is created, the concrete location of it can't exist inverse.

A Cloud Storage saucepan stores all of our files and it ties up to a concrete location. For example (us-fundamental from the screenshot above)

Firebase storage allows usa to create multiple buckets with dissimilar locations.

Click washed.

Choose An Image

Choose an image file from a user by attaching a change event to the input element with the type attribute set to file.

HTML

          <input blazon="file" onchange="uploadImage(e)" />        

JavaScript

          function uploadImage(east) {   const file = e.target.files[0]   console.log(file); }        

Then, we can accept admission to the actual file and its information using the event object eastward.target.files[0]

Upload An Image

To upload a file to the Firebase Cloud Storage, we demand two pieces of information:

  • The location path that we desire to upload a file into, and
  • The actual File

Nosotros tin specify the location path every bit an argument to the ref() method.

          firebase     .storage()     .ref('images/' + file.proper name)     .put(file);        

This volition create a folder called images, if it could non find one, and store the actual file inside it with the file name mentioned in the location path after the slash (/).

Then, the put() method uploads the file that is passed into as an argument to the given location path.

There is another way of specifying the file path, which is using child() method.

          firebase     .storage()     .ref('images')     .child(file.name)     .put(file);        

The above lawmaking does exactly the aforementioned affair as the previous case.

This won't work if you test it out at this point.

This is because

By default, Firebase Cloud Storage has security rules in place that can Merely allow logged-in users to read and write data. 🔒

Let's change that.

Go to the Storage Rules tab and alter the line from

          allow read, write: if request.auth.uid != zilch;        

To

          let read, write: if true;        

🛑 Warning: The in a higher place security is really allowing anyone to read and write to the Cloud Storage bucket. I use this for sit-in purposes Just.

Multiple Storage Buckets

We can also create multiple buckets with different locations.

If you utilise multiple storage buckets, you will have to explicitly pass the bucket URL to the storage() method equally an argument.

          firebase     .app()     .storage('gs://your-project-proper name.appspot.com/')     .ref('images')     .child(file.proper name)     .put(file);        

To get the bucket URL, go to Storage Files URL (can be found at the summit left).

Go An Image URL

To get a single file, specify the path with the folder and file names inside the ref() method and run getdownloadURL() method on it.

          firebase   .storage()   .ref('images/gold-retriever.jpg')   .getDownloadURL()   .and then(imgUrl => {     console.log(imgUrl);   });                  

The getDownloadURL() method will return a promise, and the actual file URL will be returned to the so() callback function specified in the parameter imgUrl.

Upload Multiple Files

To upload multiple images at once, add the multiple aspect to the input element.

HTML

          <input type="file" onchange="uploadMultipleImages(e)" multiple />                  

And then, loop through the files object, which is a FileList object not an actual JavaScript array. So I am using for of to iterate over and upload information technology to the Deject Storage.

forEach() won't piece of work equally they are not an acutal assortment and yous can catechumen information technology to an array like this: Array.epitome.slice.call(files)

JavaScript

          office uploadMultipleImages(e) {   let files = e.target.files;    for (const file of files) {     firebase       .storage()       .ref('images')       .kid(file.name)       .put(file);   } }        

Get All Images

The listAll() method volition get all the file URLs in a given location path.

          firebase     .storage()     .ref('images')     .listAll()     .so(snap => {       snap.items.forEach(itemRef => {         itemRef.getDownloadURL().and then(imgUrl => {           console.log(imgUrl)         });       })     })        

Inside the then() callback function, loop through the items array on the snapshot object.

So, call getDownloadURL() method on the itemRef object which returns the actual file URLs inside the so() callback part once more specified in the parameter imgUrl.

Delete A File

Notice the location path of a file and delete it using delete() method.

          firebase   .storage()   .ref('images/golden-retriever.jpg')   .delete()   .then(role() {     console.log('File deleted successfully');   }).grab(part(error) {   console.log('error occured'); });        

Firebase Storage With Hallmark Demo

In this section, you're going to acquire how to upload a profile image with Hallmark.

To get this working, I am going to dissever this into FOUR parts

  • Create A New Firebase Business relationship
  • Firebase Storage Construction & Security Rules
  • Upload Logged-In User's Profile Flick
  • Get Logged-In User's Profile Picture

Create A New User Account

Enable Electronic mail/Password sign-in method: Go to Authentication Tab → Sign-in Method → Choose Email/Password and Enable it.

Here is the unproblematic signup course that has four inputs:

  • email,
  • password,
  • file, and
  • signup push

I as well accept an prototype element at the bottom to show the contour image once it'due south uploaded to the Cloud Storage.

alphabetize.html

          <!Doctype html> <head>   <title>Larn Firebase Storage Apace</title>   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/two.3.0/semantic.min.css" /> </head> <body>   <div course="ui two column middle aligned eye aligned grid">     <div class="column">       <form course="ui large class">         <div course="ui stacked secondary segment" >           <div class="field">             <div class="ui left icon input large">               <i class="user icon"></i>               <input type="text" placeholder="E-mail accost" id="email" />             </div>           </div>           <div class="field">             <div class="ui left icon input large">               <i class="lock icon"></i>               <input type="text" placeholder="Password" id="pword" />             </div>           </div>           <div class="field">             <div class="ui left icon input large">               <i class="epitome icon"></i>               <input blazon="file" id="fileUploader" />             </div>           </div>           <div course=" ui fluid large teal submit push button" onclick="signUpUser()">Sign Up</div>         </div>         <div course="ui large prototype">           <img id="img">         </div>       </form>     </div>   </div>   <script src="https://www.gstatic.com/firebasejs/7.9.0/firebase-app.js"></script>   <script src="https://www.gstatic.com/firebasejs/7.9.0/firebase-auth.js"></script>   <script src="https://www.gstatic.com/firebasejs/7.ix.0/firebase-storage.js"></script>   <script src="app.js"></script> </body> </html>        

I employ the Semantic-UI CSS framework for this instance.

At the lesser, brand sure to add together the post-obit Firebase SDKs:

  • App
  • Authentication, and
  • Storage.

⚠️ The latest version of Firebase SDK has some problems with CORS at least at the time of this writing. So make sure to apply the Firebase SDK version of seven.ix.0 to avoid a CORS effect.

In the JavaScript file, replace the firebaseConfig code with yours. You lot can find information technology at Firebase Project Overview at the elevation ⚙ → Project Setting Register App

app.js

          var firebaseConfig = {   apiKey: "*****************",   authDomain: "*****************",   databaseURL: "*****************",   projectId: "*****************",   storageBucket: "*****************",   messagingSenderId: "*****************",   appId: "*****************",   measurementId: "*****************" };  // Initialize Firebase firebase.initializeApp(firebaseConfig);  const email = document.getElementById('email'),   pword = document.getElementById('pword'),   fileUploader = certificate.getElementById('fileUploader');  let file = {};  fileUploader.addEventListener('change', function (e) {   file = due east.target.files[0]; })  office signUpUser() {   firebase.auth().createUserWithEmailAndPassword(email.value, pword.value).then(auth => {     console.log(auth)   }).catch(fault => {     console.log(mistake.message)   }) }        

Once a new user is created, an auth object will be returned to the and then() callback function specified in the parameter auth.

Firebase Storage Structure & Security Rules

Earlier uploading a file to the storage, let's structure the files in a way that just authenticated users can read and write.

To do that, I am going to create a binder chosen users so create another binder using the user's UID as a folder proper name. Then, store the file in there with the fixed name chosen profile.jpg.

Assuming I will exist just uploading .jpg files just for the simplicity sake.

Go to Firebase ConsoleStorage Section → Choose Rules Tab from the top.

So, add the following security dominion code in in that location.

          rules_version = '2'; service firebase.storage {   match /b/{saucepan}/o {     match /users/{uid}/{profileImage} {       permit read, write: if asking.auth.uid == uid;     }   } }        

The Cloud Storage security rule below gives any user read and write permission to the location path ( /users/{uid}/{profileImage}), as long as the logged-in user'southward UID (request.auth.uid) matches with the uid which is referring to the place holder {uid} mentioned in the location path.

Upload Logged-In User'southward Contour Flick

In one case a new user account is created, inside the then() callback role, upload the profile picture with the user's UID.

          function signUpUser() {   firebase.auth().createUserWithEmailAndPassword(electronic mail.value, pword.value).then(auth => {     firebase       .storage()       .ref("users")       .child(auth.user.uid + "/profile.jpg")       .put(file);    }).catch(error => {     console.log(error.message)   }) }        

And the file structure should be something like this in the Firebase Storage Dashboard.

Get Logged-In User'south Contour Picture

Invoke onAuthStateChange() method to check if any user is logged in.

If at that place is a user, and so get the contour moving picture by calling getDowloadURL() method.

Within the then() callback function, the actual image URL specified in the parameter called imgURL.

And so, ready it to the img element to display it on the browser.

          const img = document.getElementById('img');  firebase.auth().onAuthStateChanged(user => {   if (user) {     firebase       .storage()       .ref("users")       .kid(user.uid + "/profile.jpg")       .getDownloadURL()       .and so(imgUrl => {         img.src = imgUrl;       });     console.log(user)   } })        

There you lot have it.

Discover the full source code on Github.

If you lot take whatever suggestions, feedback or if anything is unclear in this article, please accomplish out to me by commenting below.

I am looking forward to hearing from you and Happy Coding!

boycepenot1954.blogspot.com

Source: https://softauthor.com/learn-firebase-cloud-storage-quickly-guide/

0 Response to "Firebase Record Path When Uploading to Storage"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel