How To Upload Multiple Files On Firebase
Firebase Storage is a groovy way to store all the asset files for your projects in a single identify.
You can store pretty much any files such equally:
- images,
- videos,
- audio,
- documents, etc
You can also create folders to organize other files or folders.
Uploading files and downloading file URLs are super easy and we can easily protect them using Firebase Storage Security Rules, which is very like to Cloud Firestore Security Rules.
Table of Contents
- Setting Upward Firebase Storage
- Choose An Paradigm
- Upload An Image
- Multiple Storage Buckets
- Go An Image
- Upload Multiple Files
- Get All Images
- Delete A File
- Firebase Storage With Hallmark Demo
- Create A New Firebase Account
- Firebase Storage Structure & Security Rules
- Upload Logged-In User'southward Contour Picture
- Get Logged-In User'south Contour Picture
Enable Firebase Storage
Enable Firebase Storage by clicking the Get Started button later logging into the Firebase account.
The default Deject StorageSecurity Dominion will be set up to "merely authenticated users can read and write data",
Click next.
Then, it gives us a warning saying that once the Firebase Cloud Storage saucepan is created, the physical location of it can't be inverse.
A Cloud Storage bucket stores all of our files and it ties upwardly to a physical location. For example (united states of america-central from the screenshot higher up)
Firebase storage allows us to create multiple buckets with unlike locations.
Click done.
Cull An Paradigm
Cull an prototype file from a user past 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(e) { const file = east.target.files[0] console.log(file); }
Then, we can have access to the actual file and its information using the event object east.target.files[0]
Upload An Prototype
To upload a file to the Firebase Cloud Storage, we need ii pieces of information:
- The location path that we want to upload a file into, and
- The actual File
Nosotros can specify the location path as an argument to the ref()
method.
firebase .storage() .ref('images/' + file.name) .put(file);
This will create a folder called images, if it could not find i, and store the actual file inside it with the file proper noun mentioned in the location path after the slash (/).
And then, the put()
method uploads the file that is passed into as an argument to the given location path.
In that location is another style of specifying the file path, which is using child()
method.
firebase .storage() .ref('images') .kid(file.name) .put(file);
The to a higher place code does exactly the aforementioned thing equally the previous example.
This won't work if you exam information technology out at this signal.
This is because…
By default, Firebase Cloud Storage has security rules in identify that can ONLY allow logged-in users to read and write data. 🔒
Allow'southward modify that.
Go to the Storage → Rules tab and change the line from
allow read, write: if asking.auth.uid != null;
To
allow read, write: if truthful;
🛑 Warning: The above security is actually assuasive anyone to read and write to the Deject Storage saucepan. I utilize this for sit-in purposes ONLY.
Multiple Storage Buckets
We can also create multiple buckets with different locations.
If you use multiple storage buckets, you will have to explicitly pass the bucket URL to the storage()
method as an argument.
firebase .app() .storage('gs://your-project-name.appspot.com/') .ref('images') .child(file.name) .put(file);
To get the bucket URL, go to Storage → Files → URL (can be found at the top left).
Get An Image URL
To go a single file, specify the path with the binder and file names within the ref()
method and run getdownloadURL()
method on it.
firebase .storage() .ref('images/aureate-retriever.jpg') .getDownloadURL() .so(imgUrl => { panel.log(imgUrl); });
The getDownloadURL()
method will return a hope, and the actual file URL volition be returned to the then()
callback part specified in the parameter imgUrl
.
Upload Multiple Files
To upload multiple images at one time, add the multiple
attribute to the input element.
HTML
<input type="file" onchange="uploadMultipleImages(east)" multiple />
Then, loop through the files object, which is a FileList
object non an actual JavaScript assortment. So I am using for of
to iterate over and upload it to the Deject Storage.
forEach()
won't work every bit they are not an acutal array and you tin convert information technology to an array like this: Array.paradigm.piece.call(files)
JavaScript
function uploadMultipleImages(e) { let files = eastward.target.files; for (const file of files) { firebase .storage() .ref('images') .child(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() .then(snap => { snap.items.forEach(itemRef => { itemRef.getDownloadURL().and so(imgUrl => { console.log(imgUrl) }); }) })
Inside the then()
callback function, loop through the items
array on the snapshot
object.
So, phone call getDownloadURL()
method on the itemRef
object which returns the bodily file URLs inside the and so()
callback office again specified in the parameter imgUrl
.
Delete A File
Observe the location path of a file and delete it using delete()
method.
firebase .storage() .ref('images/golden-retriever.jpg') .delete() .then(function() { panel.log('File deleted successfully'); }).catch(office(error) { console.log('error occured'); });
Firebase Storage With Authentication Demo
In this section, you're going to larn how to upload a contour epitome with Authentication.
To get this working, I am going to split this into Four parts
- Create A New Firebase Account
- Firebase Storage Structure & Security Rules
- Upload Logged-In User's Contour Movie
- Get Logged-In User'southward Contour Picture
Create A New User Business relationship
Enable Email/Password sign-in method: Get to Authentication Tab → Sign-in Method → Choose Email/Password and Enable it.
Hither is the simple signup form that has four inputs:
- email,
- password,
- file, and
- signup button
I also have an epitome element at the lesser to show the profile prototype one time it'due south uploaded to the Cloud Storage.
index.html
<!Doctype html> <head> <title>Learn Firebase Storage Quickly</championship> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.iii.0/semantic.min.css" /> </caput> <body> <div grade="ui two column middle aligned center aligned grid"> <div class="column"> <form class="ui big form"> <div class="ui stacked secondary segment" > <div class="field"> <div class="ui left icon input large"> <i class="user icon"></i> <input type="text" placeholder="E-post address" id="electronic mail" /> </div> </div> <div class="field"> <div class="ui left icon input large"> <i class="lock icon"></i> <input type="text" placeholder="Countersign" id="pword" /> </div> </div> <div grade="field"> <div class="ui left icon input large"> <i class="epitome icon"></i> <input blazon="file" id="fileUploader" /> </div> </div> <div grade=" ui fluid big teal submit push" onclick="signUpUser()">Sign Up</div> </div> <div class="ui large image"> <img id="img"> </div> </course> </div> </div> <script src="https://www.gstatic.com/firebasejs/7.9.0/firebase-app.js"></script> <script src="https://world wide web.gstatic.com/firebasejs/7.9.0/firebase-auth.js"></script> <script src="https://www.gstatic.com/firebasejs/7.9.0/firebase-storage.js"></script> <script src="app.js"></script> </body> </html>
I utilise the Semantic-UI CSS framework for this case.
At the bottom, brand sure to add the following Firebase SDKs:
- App
- Hallmark, and
- Storage.
⚠️ The latest version of Firebase SDK has some problems with CORS at least at the time of this writing. Then make sure to use the Firebase SDK version of 7.9.0 to avoid a CORS issue.
In the JavaScript file, replace the firebaseConfig code with yours. You tin find it at Firebase → Projection Overview at the top ⚙ → 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 = certificate.getElementById('pword'), fileUploader = document.getElementById('fileUploader'); let file = {}; fileUploader.addEventListener('change', part (e) { file = e.target.files[0]; }) function signUpUser() { firebase.auth().createUserWithEmailAndPassword(email.value, pword.value).then(auth => { console.log(auth) }).take hold of(error => { console.log(fault.message) }) }
Once a new user is created, an auth
object will be returned to the then()
callback function specified in the parameter auth
.
Firebase Storage Structure & Security Rules
Before uploading a file to the storage, permit'south construction the files in a style that only authenticated users can read and write.
To do that, I am going to create a folder called users then create some other folder using the user's UID equally a folder proper name. Then, store the file in there with the fixed name called profile.jpg.
Bold I will exist only uploading .jpg files just for the simplicity sake.
Go to Firebase Console → Storage Section → Choose Rules Tab from the top.
Then, add the following security rule code in there.
rules_version = 'ii'; service firebase.storage { match /b/{bucket}/o { match /users/{uid}/{profileImage} { allow read, write: if request.auth.uid == uid; } } }
The Deject Storage security rule below gives whatsoever user read and write permission to the location path ( /users/{uid}/{profileImage}
), equally long as the logged-in user's UID (request.auth.uid
) matches with the uid
which is referring to the identify holder {uid}
mentioned in the location path.
Upload Logged-In User'due south Profile Moving picture
Once a new user account is created, inside the then()
callback role, upload the contour picture with the user's UID.
role signUpUser() { firebase.auth().createUserWithEmailAndPassword(e-mail.value, pword.value).and then(auth => { firebase .storage() .ref("users") .child(auth.user.uid + "/contour.jpg") .put(file); }).catch(fault => { console.log(mistake.message) }) }
And the file structure should be something like this in the Firebase Storage Dashboard.
Get Logged-In User's Profile Flick
Invoke onAuthStateChange()
method to check if any user is logged in.
If there is a user, so get the profile picture past calling getDowloadURL()
method.
Inside the so()
callback part, the actual image URL specified in the parameter called imgURL
.
Then, gear up it to the img
chemical element to brandish it on the browser.
const img = document.getElementById('img'); firebase.auth().onAuthStateChanged(user => { if (user) { firebase .storage() .ref("users") .child(user.uid + "/profile.jpg") .getDownloadURL() .then(imgUrl => { img.src = imgUrl; }); console.log(user) } })
There you have it.
Find the full source code on Github.
If you have any suggestions, feedback or if anything is unclear in this commodity, please reach out to me by commenting beneath.
I am looking forward to hearing from you lot and Happy Coding!
Source: https://softauthor.com/learn-firebase-cloud-storage-quickly-guide/
Posted by: carrollcieved.blogspot.com
0 Response to "How To Upload Multiple Files On Firebase"
Post a Comment