Friday, 9 September 2016

Firebase in Android - Storage

With reference from my last blog here, now we go forward towards the next step i.e learning the concept of Storage in Firebase.
Firebase Storage lets you upload and share user generated content, such as images and video, which allows you to build rich media content into your apps. Firebase Storage stores this data in a Google Cloud Storage bucket. Firebase Storage lets you securely upload these files directly from mobile devices and web browsers, handling spotty networks with ease.

-Prerequisites:
Install the Firebase SDK.
Add your app to your Firebase project in the Firebase console.

-Add Firebase Storage to your app:
 Add the dependencies for Firebase Storage to your build.gradle file:

compile 'com.google.firebase:firebase-storage:9.4.0'
compile 'com.google.firebase:firebase-auth:9.4.0'

-Set up Firebase Storage:
The first step in accessing your storage bucket is to create an instance of FirebaseStorage:

FirebaseStorage storage = FirebaseStorage.getInstance();

-Create a Reference:
Create a reference to upload, download, or delete a file, or to get or update its metadata. A reference can be thought of as as pointer to a file in the cloud. References are lightweight, so you can create as many as you need. They are also reusable for multiple operations. You can create a reference as follows:

// Create a storage reference from our app
StorageReference storageRef = storage.getReferenceFromUrl("gs://<your-bucket-name>");

gs://<your-firebase-storage-bucket> You can find this URL the Storage section of the Firebase console.
You can create a reference to a location lower in the tree, say 'images/space.jpg' by using the getChild() method on an existing reference.

// Create a child reference
// imagesRef now points to "images"
StorageReference imagesRef = storageRef.child("images");

// Child references can also take paths
// spaceRef now points to "users/me/profile.png
// imagesRef still points to "images"
StorageReference spaceRef = storageRef.child("images/space.jpg");

-Limitations on References:
Reference paths and names can contain any sequence of valid Unicode characters, but certain restrictions are imposed including:
  • Total length of reference.fullPath must be between 1 and 1024 bytes when UTF-8 encoded.
  • No Carriage Return or Line Feed characters.
  • Avoid using #, [, ], *, or ?, as these do not work well with other tools such as the Firebase Realtime Database or gsutil.
-Upload Files:
To upload a file to Firebase Storage, you first create a reference to the full path of the file, including the file name.

// Create a storage reference from our app
StorageReference storageRef = storage.getReferenceFromUrl("gs://<your-bucket-name>");
// Create a reference to 'images/mountains.jpg'
StorageReference mountainImagesRef = storageRef.child("images/mountains.jpg");

-Upload from data in memory:
The putData() method is the simplest way to upload a file to Firebase Storage. putData() takes a byte[] and returns an UploadTask that you can use to manage and monitor the status of the upload.

// Get the data from an ImageView as bytes
imageView.setDrawingCacheEnabled(true);
imageView.buildDrawingCache();
Bitmap bitmap = imageView.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();

UploadTask uploadTask = mountainsRef.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
        // Handle unsuccessful uploads
    }
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
        // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
        Uri downloadUrl = taskSnapshot.getDownloadUrl();
    }
});

-Upload from a local file:
You can upload local files on the device, such as photos and videos from the camera, with the putFile() method. putFile() takes a File and returns an UploadTask which you can use to manage and monitor the status of the upload.

Uri file = Uri.fromFile(new File("path/to/images/rivers.jpg"));
StorageReference riversRef = storageRef.child("images/"+file.getLastPathSegment());
uploadTask = riversRef.putFile(file);

// Register observers to listen for when the download is done or if it fails
uploadTask.addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
        // Handle unsuccessful uploads
    }
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
        Uri downloadUrl = taskSnapshot.getDownloadUrl();
    }
});

-Download files:
Download to a local file
The getFile() method downloads a file directly to a local device. Use this if your users want to have access to the file while offline or to share the file in a different app. getFile() returns a DownloadTask which you can use to manage your download and monitor the status of the download.

// Create a storage reference from our app to the image
StorageReference islandRef = storageRef.child("images/island.jpg");

File localFile = File.createTempFile("images", "jpg");

islandRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
        // Local temp file has been created
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
        // Handle any errors
    }
});

That's all of this tutorial. Try this and wait for the next one to proceed further.

3 comments:

  1. A mini excavator is a compact and versatile piece of construction equipment designed for small to medium-sized projects. Despite its smaller size, it is powerful and efficient, capable of digging, trenching, and demolishing tasks in tight spaces where larger machines can't operate.
    https://asianexcavators.com/

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete

  3. A Bangkok VPS is a virtual private server located in Bangkok, Thailand. This means it's a type of online computer that you can use to store files, run applications, or host websites. It's like having your own private space on a powerful computer that is shared with others. By choosing a server in Bangkok,

    ReplyDelete