Cloud Storage for Firebase allows you to quickly and easily upload files to a Cloud Storage bucket provided and managed by Firebase.
Upload Files
To upload a file to Cloud Storage, you first create a reference to the full path of the file, including the file name.
// Create a storage reference from our appfinalstorageRef=FirebaseStorage.instance.ref();// Create a reference to "mountains.jpg"finalmountainsRef=storageRef.child("mountains.jpg");// Create a reference to 'images/mountains.jpg'finalmountainImagesRef=storageRef.child("images/mountains.jpg");// While the file names are the same, the references point to different filesassert(mountainsRef.name==mountainImagesRef.name);assert(mountainsRef.fullPath!=mountainImagesRef.fullPath);
Once you've created an appropriate reference, you then call the putFile()
, putString()
, or putData()
method to upload the file to Cloud Storage.
You cannot upload data with a reference to the root of your Cloud Storage bucket. Your reference must point to a child URL.
Upload from a file
To upload a file, you must first get the absolute path to its on-device location. For example, if a file exists within the application's documents directory, use the official path_provider
package to generate a file path and pass it to putFile()
:
DirectoryappDocDir=awaitgetApplicationDocumentsDirectory();StringfilePath='${appDocDir.absolute}/file-to-upload.png';Filefile=File(filePath);try{awaitmountainsRef.putFile(file);}onfirebase_core.FirebaseExceptioncatch(e){// ...}
Upload from a String
You can upload data as a raw, base64
, base64url
, or data_url
encoded string using the putString()
method. For example, to upload a text string encoded as a Data URL:
StringdataUrl='data:text/plain;base64,SGVsbG8sIFdvcmxkIQ==';try{awaitmountainsRef.putString(dataUrl,format:PutStringFormat.dataUrl);}onFirebaseExceptioncatch(e){// ...}
Uploading raw data
You can upload lower-level typed data in the form of a Uint8List
for those cases where uploading a string or File
is not practical. In this case, call the putData()
method with your data:
try{// Upload raw data.awaitmountainsRef.putData(data);}onfirebase_core.FirebaseExceptioncatch(e){// ...}
Get a download URL
After uploading a file, you can get a URL to download the file by calling the getDownloadUrl()
method on the Reference
:
awaitmountainsRef.getDownloadURL();
Add File Metadata
You can also include metadata when you upload files. This metadata contains typical file metadata properties such as contentType
(commonly referred to as MIME type). The putFile()
method automatically infers the MIME type from the File
extension, but you can override the auto-detected type by specifying contentType
in the metadata. If you do not provide a contentType
and Cloud Storage cannot infer a default from the file extension, Cloud Storage uses application/octet-stream
. See Use File Metadata.
try{awaitmountainsRef.putFile(file,SettableMetadata(contentType:"image/jpeg",));}onfirebase_core.FirebaseExceptioncatch(e){// ...}
Manage Uploads
In addition to starting uploads, you can pause, resume, and cancel uploads using the pause()
, resume()
, and cancel()
methods. Pause and resume events raise pause
and progress
state changes respectively. Canceling an upload causes the upload to fail with an error indicating that the upload was canceled.
finaltask=mountainsRef.putFile(largeFile);// Pause the upload.boolpaused=awaittask.pause();print('paused, $paused');// Resume the upload.boolresumed=awaittask.resume();print('resumed, $resumed');// Cancel the upload.boolcanceled=awaittask.cancel();print('canceled, $canceled');
Monitor Upload Progress
You can listen to a task's event stream to handle success, failure, progress, or pauses in your upload task:
Event Type | Typical Usage |
---|---|
TaskState.running | Emitted periodically as data is transferred and can be used to populate an upload/download indicator. |
TaskState.paused | Emitted any time the task is paused. |
TaskState.success | Emitted when the task has successfully completed. |
TaskState.canceled | Emitted any time the task is canceled. |
TaskState.error | Emitted when the upload has failed. This can happen due to network timeouts, authorization failures, or if you cancel the task. |
mountainsRef.putFile(file).snapshotEvents.listen((taskSnapshot){switch(taskSnapshot.state){caseTaskState.running:// ...break;caseTaskState.paused:// ...break;caseTaskState.success:// ...break;caseTaskState.canceled:// ...break;caseTaskState.error:// ...break;}});
Error Handling
There are a number of reasons why errors may occur on upload, including the local file not existing, or the user not having permission to upload the desired file. You can find more information about errors in the Handle Errors section of the docs.
Full Example
A full example of an upload with progress monitoring and error handling is shown below:
finalappDocDir=awaitgetApplicationDocumentsDirectory();finalfilePath="${appDocDir.absolute}/path/to/mountains.jpg";finalfile=File(filePath);// Create the file metadatafinalmetadata=SettableMetadata(contentType:"image/jpeg");// Create a reference to the Firebase Storage bucketfinalstorageRef=FirebaseStorage.instance.ref();// Upload file and metadata to the path 'images/mountains.jpg'finaluploadTask=storageRef.child("images/path/to/mountains.jpg").putFile(file,metadata);// Listen for state changes, errors, and completion of the upload.uploadTask.snapshotEvents.listen((TaskSnapshottaskSnapshot){switch(taskSnapshot.state){caseTaskState.running:finalprogress=100.0*(taskSnapshot.bytesTransferred/taskSnapshot.totalBytes);print("Upload is $progress% complete.");break;caseTaskState.paused:print("Upload is paused.");break;caseTaskState.canceled:print("Upload was canceled");break;caseTaskState.error:// Handle unsuccessful uploadsbreak;caseTaskState.success:// Handle successful uploads on complete// ...break;}});
Now that you've uploaded files, let's learn how to download them from Cloud Storage.