Upload Files with Cloud Storage for Unity

Cloud Storage allows developers to quickly and easily upload files to a Google Cloud Storage bucket provided and managed by Firebase.

Create a Reference

To upload a file, first create a Cloud Storage reference to the location in Cloud Storage you want to upload the file to.

You can create a reference by appending child paths to the storage root:

// Create a root reference
Firebase.Storage.StorageReference storage_ref = storage.Reference();

// Create a reference to "mountains.jpg"
Firebase.Storage.StorageReference mountains_ref = storage_ref.Child("mountains.jpg");

// Create a reference to 'images/mountains.jpg'
Firebase.Storage.StorageReference mountain_images_ref = storage_ref.Child("images/mountains.jpg");

// While the file names are the same, the references point to different files
mountains_ref.Name == mountain_images_ref.Name;           // true
mountains_ref.Path == mountain_images_ref.Path; // false

You cannot upload data with a reference to the root of your Google Cloud Storage bucket. Your reference must point to a child URL.

Upload Files

Once you have a reference, you can upload files to Cloud Storage in two ways:

  1. Upload from a byte array in memory
  2. Upload from a file path representing a file on device

Upload from data in memory

The PutBytesAsync() method is the simplest way to upload a file to Cloud Storage. PutBytesAsync() takes a byte[] and returns a System.Task<Firebase.Storage.StorageMetadata> which will contain information about the file when the task completes. You can optionally use an IProgress<UploadState> (typically StorageProgress) to monitor your upload status.

// Data in memory
var custom_bytes = new byte[] { ... };

// Create a reference to the file you want to upload
Firebase.Storage.StorageReference rivers_ref = storage_ref.Child("images/rivers.jpg");

// Upload the file to the path "images/rivers.jpg"
rivers_ref.PutData(custom_bytes).ContinueWith(task => {
        if (task.IsFaulted || task.IsCancelled) {
            DebugLog(task.Exception.ToString());
            // Uh-oh, an error occurred!
        } else {
            // Metadata contains file metadata such as size, content-type, and download URL.
            Firebase.Storage.Metadata metadata = task.Result;
            string download_url = metadata.DownloadUrl();
            DebugLog("Finished uploading...");
            DebugLog("download url = " + download_url);
        }
    });

Upload from a local file

You can upload local files on the devices, such as photos and videos from the camera, with the PutFileAsync() method. PutFileAsync() takes a string representing the path to the file and returns a System.Task<Firebase.Storage.StorageMetadata> which will contain information about the file when the task completes. You can optionally use an IProgress<UploadState> (typically StorageProgress) to monitor your upload status.

// File located on disk
string local_file = ...

// Create a reference to the file you want to upload
Firebase.Storage.StorageReference rivers_ref = storage_ref.Child("images/rivers.jpg");

// Upload the file to the path "images/rivers.jpg"
rivers_ref.PutFileAsync(localFile).ContinueWith(task => {
        if (task.IsFaulted || task.IsCancelled) {
            DebugLog(task.Exception.ToString());
            // Uh-oh, an error occurred!
        } else {
            // Metadata contains file metadata such as size, content-type, and download URL.
            Firebase.Storage.Metadata metadata = task.Result;
            string download_url = metadata.DownloadUrl();
            DebugLog("Finished uploading...");
            DebugLog("download url = " + download_url);
        }
    });

If you want to actively monitor your upload, you can use a StorageProgress class or your own class that implements IProgress, with the PutFileAsync() or PutBytesAsync() methods. See Manage Uploads for more information.

Add File Metadata

You can also include metadata when you upload files. This metadata contains typical file metadata properties such as Name, Size, and ContentType (commonly referred to as MIME type). The PutFileAsync() method automatically infers the content type from the filename 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 the Use File Metadata section for more information about file metadata.

// Create storage reference
Firebase.Storage.StorageReference mountains_ref = storage_ref.Child("images/mountains.jpg");

var custom_bytes = new byte[] { ... };

// Create file metadata including the content type
var new_metadata = new Firebase.Storage.MetadataChange();
new_metadata.ContentType = "image/jpeg";

// Upload data and metadata
mountains_ref.PutBytesAsync(custom_bytes, new_metadata, null,
                            CancellationToken.None, null);  // .ContinueWith(...
// Upload file and metadata
mountains_ref.PutFileAsync(local_file, new_metadata, null,
                           CancellationToken.None, null);  // .ContinueWith(...

Monitor Upload Progress

You can attach listeners to uploads in order to monitor the progress of the upload. The listener follows the standard System.IProgress interface. You can use an instance of the StorageProgress class, to provide your own Action<T> as a callback for progress ticks.

// Start uploading a file
var task = storage_ref.Child("images/mountains.jpg")
    .PutFileAsync(local_file, null, new StorageProgress(state => {
      // called periodically during the upload
      DebugLog(String.Format("Progress: {0} of {1} bytes transferred.",
                             state.BytesTransferred, state.TotalByteCount));
    }), CancellationToken.None, null);
task.ContinueWith(resultTask => {
        if (!resultTask.IsFaulted && !resultTask.IsCancelled) {
            DebugLog("Upload finished.");
        }
    });

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.

Next Steps

Now that you've uploaded files, let's learn how to download them from Cloud Storage.

Send feedback about...

Need help? Visit our support page.