Setting up Firebase to Android Studio project
Choose Storage entry and click "Upload and download file with Firebase Storage", this panel will appear:
Choose "Connect to Firebase", Android Studio will launch your default browser and you must be logged in by Google account to continue, let follow these simple steps on Google developer console and when you return to Android Studio, you have this dialog:
Choose an existed project on your Firebase console (or create a new project) and click "Connect to Firebase". After this process completed, click at "Add Firebase Storage to your app" (entry (2)), you'll have this dialog:
Click "Accept Changes" to add these dependencies and google-services.json file to your project. You now have completed setting up environment work!
As you can see at the right panel, at the entry (3), (4) and (5), these are tutorials about initializing
StorageReference
and download/upload files from/to Firebase Storage:Open Firebase console page and select your project, choose Storage in the left navigation column and select Rules tab, you'll see this code:
In this tutorial, I would like to allow unauthenticated users to access and upload files to keep things simple. So on the line
allow read, write: if request.auth != null;
, change !=
to ==
and click the PUBLISH button:Now any user of your app should be able to upload or download files from your Firebase back-end. Please remember: this is not ideal for a production environment, but within the scope of a tutorial, it will make learning about Firebase Storage a lot easier without having to dig into authentication code.
Testing Upload/Download File on Firebase console
Similar with upload, you can select a file from this page, "Download" button will appear and when click it, your file will be downloaded to your computer:
Upload a Byte array from Android application
assets
folder and a text file to raw
folder like this:
In order to access your Firebase Storage files, you'll need to first get a reference to the
FirebaseStorage
object, and then create a StorageReference
to your project's URL and the file that you want to upload. You can find your project's URL at the top of the Files section of Storage in the Firebase Console. In onCreate()
of your Activity
, provide this code:
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageReference = storage.getReferenceFromUrl("gs://filestorage-d5afb.appspot.com").child("firebase.png");
Next, we will need to get a byte array from the image file located in assets
folder. We will retrieve it as a Bitmap
, compressing it into a ByteArrayOutputStream
, and then turning that into a byte[]
. Then, you can create an UploadTask
by calling putBytes(byte[])
to upload your image to Firebase. This UploadTask
can also have an OnSuccessListener
and OnFailureListener
to handling the upload process result:
AssetManager assetManager = MainActivity.this.getAssets();
InputStream istr;
Bitmap bitmap;
try {
//get bitmap from PNG file in assets folder
istr = assetManager.open("firebase.png");
bitmap = BitmapFactory.decodeStream(istr);
//decode to byte output stream
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
byte[] data = outputStream.toByteArray();
//Upload to firebase
showProgressDialog("Upload Bitmap", "Uploading...");
UploadTask uploadTask = storageReference.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
exception.printStackTrace();
dismissProgressDialog();
Toast.makeText(MainActivity.this, "Upload Failed!", Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
dismissProgressDialog();
Toast.makeText(MainActivity.this, "Upload successful!", Toast.LENGTH_SHORT).show();
}
});
} catch (IOException e) {
e.printStackTrace();
}
In this sample project, upload process will be invoked after click a Button
, this is output:Go to Firebase Console page, you will see the new uploaded file(firebase.png):
Uploading From an InputStream
InputStream
and then upload it by using putStream(InputStream)
method of StorageReference
. Like the case above, we use an UploadTask
to upload and adding addOnSuccessListener
and addOnFailureListener
to it:
storageReference = storage.getReferenceFromUrl("gs://filestorage-d5afb.appspot.com").child("test_upload.txt");
//Upload input stream to Firebase
showProgressDialog("Upload File", "Uploading text file...");
InputStream stream = getResources().openRawResource(R.raw.test);
UploadTask uploadTask = storageReference.putStream(stream);
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
exception.printStackTrace();
dismissProgressDialog();
Toast.makeText(MainActivity.this, "Upload Failed!", Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
dismissProgressDialog();
Toast.makeText(MainActivity.this, "Upload successful!", Toast.LENGTH_SHORT).show();
}
});
And this is output of my sample project:
Go to Firebase Console page, you will see new uploaded file named test_upload.txt:
NOTE
: You also have another upload option is File. Uploading an existing file is just as easy: simply get a reference to the file and call putFile(Uri)
with a URI pointing to your file.
Conclusions
InputStream
or File
. Up to Part 2, I will talk about downloading file from Firebase Storage, coming soon!
References: