With the Cloud Storage for Firebase Android SDK, how do putBytes, putStream and putFile differ, and how do you get a download URL afterwards?
answer
- memory, stream or Uri
- all three return an UploadTask
- never upload to the bucket root
- ask the reference after success
- missing contentType becomes octet-stream
basics
~20 sAll three upload to a StorageReference and return an UploadTask: putBytes needs the whole byte array in memory, putStream reads an InputStream, putFile reads a file or content Uri. Ask the reference for getDownloadUrl() once the task succeeds.
solid answer
~40 sYou build a `StorageReference` below the bucket root, such as `child("recipes/$uid/$photoId.jpg")`, and call one of three methods, each returning an `UploadTask`. `putBytes(ByteArray)` is the simplest but holds the whole file in memory; `putStream(InputStream)` uploads from any stream; `putFile(Uri)` takes a `file://` or `content://` Uri, so a photo-picker result uploads directly, and it is the only one with an overload that resumes a saved upload session. The task's listeners run on the main thread unless you pass an `Executor`, or you can `await()` it from a coroutine. The download URL is a separate call: once the upload succeeds, call `getDownloadUrl()` on the same reference (`downloadUrl` in Kotlin), usually chained with `continueWithTask`. Set `contentType` through `StorageMetadata` when it cannot be inferred, or the object is stored as `application/octet-stream`.
code
kotlin · 12 linesimport android.net.Uri
import com.google.firebase.Firebase
import com.google.firebase.storage.storage
import com.google.firebase.storage.storageMetadata
import kotlinx.coroutines.tasks.await
suspend fun uploadRecipePhoto(uid: String, photoId: String, photo: Uri): Uri {
val ref = Firebase.storage.reference.child("recipes/$uid/$photoId.jpg")
val metadata = storageMetadata { contentType = "image/jpeg" }
ref.putFile(photo, metadata).await()
return ref.downloadUrl.await()
}go deeper
Recall the three put methods by input type, that each returns an UploadTask, and that the download URL comes from the reference after success.
Explain why putFile scales and putBytes does not, how contentType is resolved, and why getDownloadUrl must be chained after the upload rather than run beside it.
Show you have shipped uploads: Activity-scoped listeners, re-attaching through getActiveUploadTasks, StorageException codes mapped to user messages, and no main-thread work beyond the progress update.
Weigh where upload metadata lives: Storage custom metadata for what rules must read, the app's database for what screens must query, and a path scheme that keeps per-user files separable.
## Where an upload goes **Cloud Storage for Firebase** stores files ("objects") in a bucket that Firebase manages for your project. The Android SDK never uploads to a bucket in the abstract: it uploads to a **`StorageReference`**, a pointer to one full object path such as `recipes/u42/p7.jpg`. You get one from `Firebase.storage.reference` (the bucket root) and narrow it with `child(path)`. - A reference is only a path. Creating it makes no network call and does not require the object to exist. - Two references can share a `name` (`p7.jpg`) and differ in `path`; the path is what identifies the object. - The root itself is not a valid upload target. The SDK fails the task with "Cannot upload to getRoot" if you try, so always upload to a child path. By default the bucket requires a signed-in Firebase Authentication user for any action, so an upload from a signed-out client fails until the Storage rules say otherwise (the rules language is a separate lesson). ## The three upload methods All three live on `StorageReference`, and each has an overload that also takes `StorageMetadata`. | Method | Input | Memory cost | Typical source | |---|---|---|---| | `putBytes(bytes)` | `ByteArray` | the whole file on the heap at once | a small, already-compressed thumbnail | | `putStream(stream)` | `InputStream` | buffered, chunk by chunk | data you generate or decrypt on the fly | | `putFile(uri)` | `file://` or `content://` `Uri` | buffered; the SDK opens the Uri through the `ContentResolver` | a camera capture or photo-picker result | `putFile` is the everyday choice for user photos and videos. It is also the only method with a three-argument overload, `putFile(uri, metadata, existingUploadUri)`, that continues an interrupted upload session after a process restart. `putBytes` is fine for a 50 KB avatar; for a video it invites an `OutOfMemoryError`, because the byte array has to exist before the upload starts. ## What an UploadTask gives you Each method returns an **`UploadTask`**, which is a Play services `Task<UploadTask.TaskSnapshot>` with extra controls. - `addOnSuccessListener`, `addOnFailureListener` and `addOnCompleteListener` report the outcome; a failure carries a `StorageException` with an error code such as `ERROR_NOT_AUTHORIZED` or `ERROR_CANCELED`. - `addOnProgressListener` and `addOnPausedListener` fire during the transfer. A `TaskSnapshot` exposes `bytesTransferred`, `totalByteCount`, `uploadSessionUri` and `metadata`. - `pause()`, `resume()` and `cancel()` control the transfer; a cancelled upload fails with `ERROR_CANCELED`. - Listeners added without an `Executor` run on the **main thread**, so updating a progress bar needs no thread hop. Overloads accept an `Executor`, or an `Activity` whose stop removes the listener. - From a coroutine, `await()` from kotlinx-coroutines-play-services suspends until the task finishes and throws its exception on failure. ## Content type and metadata The stored object's `contentType` decides how a browser or image loader treats the download. The SDK resolves it in this order when the upload starts: 1. The `contentType` you set in `StorageMetadata` (`storageMetadata { contentType = "image/jpeg" }` in Kotlin). 2. For `putFile`, the type the Android `ContentResolver` reports for the Uri. 3. Otherwise `application/octet-stream`. So a JPEG sent with `putBytes` and no metadata is stored as `application/octet-stream`, and a browser opening its URL offers a file download instead of showing a picture. Custom key/value pairs go in with `setCustomMetadata`, and `updateMetadata()` later changes only the properties you pass, leaving the rest untouched. ## Getting the download URL The upload result is a `TaskSnapshot`, not a URL, and the snapshot has no download-URL getter. You ask the **reference** with `getDownloadUrl()` (the `downloadUrl` property in Kotlin), which returns a `Task<Uri>` and makes its own request for the object's metadata. It must run after the upload succeeds, so you chain it: ```kotlin val ref = Firebase.storage.reference.child("recipes/$uid/$photoId.jpg") ref.putFile(photoUri).continueWithTask { task -> if (!task.isSuccessful) throw task.exception!! ref.downloadUrl }.addOnSuccessListener { url -> saveRecipePhotoUrl(url) } ``` The URL carries a long-lived token, which is why it can be shared; what that token grants and how to revoke it is worth knowing before you store URLs for private files. ## Mistakes interviewers listen for - Reading the whole video into a `ByteArray` for `putBytes`. - Expecting the URL as the upload's result, or reading it from the snapshot. - Calling `getDownloadUrl()` in parallel with the upload instead of after it; when the object does not exist yet, it fails with `ERROR_OBJECT_NOT_FOUND`. - Leaving `contentType` unset on byte or stream uploads. - Posting progress to the UI with an extra main-thread hop, or updating a destroyed Activity because the listener was not Activity-scoped.
- Why is putBytes a poor choice for a 200 MB recipe video, and what do you use instead?`putBytes` takes a `ByteArray`, so the whole video must sit on the heap before the upload starts, which on many devices ends in an `OutOfMemoryError`. `putFile` with the video's `Uri` lets the SDK open it through the `ContentResolver` and send it in chunks, starting small and growing as chunks succeed. It is also the only method that can resume a persisted upload session after the process dies.
- Which thread runs UploadTask listeners, and how do you stop them touching a stopped Activity?Without an `Executor`, the SDK posts listener callbacks to the main thread, so a progress bar can be updated directly. The upload itself keeps running through rotation or a dialog, and plain listeners stay attached. Pass the `Activity` to `addOnProgressListener` or `addOnSuccessListener` so the listener is removed when it stops, then re-attach after recreation through `getActiveUploadTasks()` on the reference.
- putBytes is the right default for large videos because it is simplest
- The upload task's result is the download URL
- Uploading to the root reference works for single files
- Storage sniffs the JPEG bytes, so contentType never needs setting
- UploadTask listeners run on a background thread and need runOnUiThread