Upload Files to Firebase Cloud Storage from a .NET MAUI App
In my previous post, I demonstrated how to pick single or multiple files from the device using FilePicker
class in a .NET MAUI application. In this post, you’ll learn how to upload them to the cloud using Cloud Storage for Firebase.
Let’s get started.
Setup in Firebase console
Create a project in the Firebase Console.
Once you’re done creating a project, you’ll be redirected to the Project Overview page.
Navigate to the Storage under the Build menu.
Click Get started.
You’ll be prompted to set up your cloud storage security and location.
For security, choose Start in test mode for now. It is good just to get started but allows anyone to read and overwrite your files. After testing, make sure to Understand Firebase Security Rules for Cloud Storage.
Click Next.
You might want to choose the location where it is closest to the user. Read the firebase documentation for more information.
Click Done.
Now, you’ve just created your Firebase Storage.
IMPORTANT: Make sure to copy the URL, but you only need that comes after the gs://.
Install NuGet package
In your Visual Studio, create a .NET MAUI project then install the NuGet package FirebaseStorage.net.
Upload a File
First, create an instance of FirebaseStorage
. Make sure to bring in Firebase.Storage
namespace. Then, paste the URL you just copied earlier:
var firebaseStorage = await new FirebaseStorage("mauifirebasedemo-3fe70.appspot.com")
Next, indicate the file name by using Child
method:
var firebaseStorage = await new FirebaseStorage("mauifirebasedemo-3fe70.appspot.com")
.Child("fileName.jpg")
You can also create a folder directory like:
var firebaseStorage = await new FirebaseStorage("mauifirebasedemo-3fe70.appspot.com")
.Child("folderName/fileName.jpg")
To upload a file, you can use PutAsync
method, and you need to pass Stream
value. If your file is coming from the FilePicker
result, you can use OpenReadAsync
, otherwise, convert the file into a Stream
value.
var fileResult = await FilePicker.PickAsync();
var fileToUpload = await fileResult.OpenReadAsync();
var firebaseStorage = await new FirebaseStorage("mauifirebasedemo-3fe70.appspot.com")
.Child(fileResult.FileName)
.PutAsync(fileToUpload);
Once the file is uploaded, it will return a download link which you can download the file from.
Here’s a quick demo of running application on Android emulator:
Well, that’s it on how you can upload your files to Firebase Cloud Storage!
Please let me know your thoughts by leaving a comment or drop me a message me on Twitter!
Cheers!