Javatpoint Logo
Javatpoint Logo

Upload files in Cloud Storage

Cloud Storage provides facilities for developers to quickly and easily upload files to the Google Cloud Storage bucket, which is provided or managed by Firebase. By default, Firebase Authentication is required for uploading files in Cloud Storage buckets. But we can modify our Firebase Security Rules for allowing un-authentication access.

Upload files in Cloud Storage

Since the default, Engine app, Google app, and Firebase share this bucket, configuring public access can also make the newly uploaded App Engine file publicly accessible. When you set up authentication, make sure to access our storage bucket again.

For uploading a file to the Cloud Storage, we will first create a reference to the full path of the file with a file name.

Once we have created an appropriate reference, we then call the putBytes(), putFile(), or putStream() method for uploading the file to Cloud Storage. We can't upload data with reference to the root of our Google Cloud Storage bucket. Our reference must point to a child URL.

Upload from data in memory

The putBytes() method is the simplest way through which we can upload a file to the Cloud Storage easily. The putBytes() method takes a byte[] and returns an UploadTask which we can use to manage and monitor the status of the upload.

Because putBytes() accepts a byte[], it requires our app to hold the entire contents of a file in memory at once. We consider putStream() or putFile() to use less memory.

Upload from a stream

The most flexible way to upload a file to Cloud Storage is the use of the putStream() method. This method takes an InputStream and returns an UploadTask, which will use to manage and monitor the status of the upload.

Upload from a local file

We can upload local files on the device with the putFile() method. This method takes a File as an input and returns an UploadTask which we can use for managing and monitoring the status of the upload.

Getting a download URL after uploading

For downloading the file, it is required that we should have a URL. For getting URL we have to call the getDownloadUrl() method on the StorageReference.

Managing Uploads

There are some additional methods available such as pause(), resume(), and cancel(), which are used to pause, resume, or cancel the uploads. Pause, and Progress state changes, respectively, in pause and resume events. Canceling the upload cause the upload to fail with an error indicating that the upload was canceled.

Full Example

The example of upload with progress monitoring and error handling is as follows:


Next TopicFirebase Hosting




Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA