Download Files with Cloud Storage for Unity

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

Create a Reference

To download a file, first create a Cloud Storage reference to the file you want to download.

You can create a reference by appending child paths to the storage root, or you can create a reference from an existing gs:// or https:// URL referencing an object in Cloud Storage.

// Create a reference with an initial file path and name
Firebase.Storage.StorageReference path_reference = storage.GetReference("images/stars.jpg");

// Create a reference from a Google Cloud Storage URI
Firebase.Storage.StorageReference gs_reference = storage.GetReferenceFromUrl("gs://bucket/images/stars.jpg");

// Create a reference from an HTTPS URL
// Note that in the URL, characters are URL escaped!
Firebase.Storage.StorageReference https_reference = storage.GetReferenceFromUrl("https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg");

Download Files

Once you have a reference, you can download files from Cloud Storage in three ways:

  1. Download to a byte array
  2. Download with a Stream
  3. Download to an specific path on the device
  4. Generate a string URL representing the file online you can then use with Unity's built in UnityWebRequest to download as an asset, audio file or in other ways supported by Unity.

Download to a byte array

Download the file to a byte buffer in memory using the GetBytes() method. This is the easiest way to quickly download a file, but it must load entire contents of your file into memory. If you request a file larger than your app's available memory, your app will crash. To protect against memory issues, make sure to set the max size to something you know your app can handle, or use another download method.

// Create a reference to the file you want to download
Firebase.Storage.StorageReference island_ref = storage_ref.Child("images/island.jpg");

// Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes)
const long maxAllowedSize = 1 * 1024 * 1024;
island_ref.GetData(maxAllowedSize).ContinueWith(task => {
        if (task.IsFaulted || task.IsCancelled) {
            DebugLog(task.Exception.ToString());
            // Uh-oh, an error occurred!
        } else {
            fileContents = Encoding.UTF8.GetString(task.Result);
            DebugLog("Finished downloading...");
            DebugLog("Contents=" + fileContents);
        }
    });

Download with a Stream

Downloading the file with a Stream allows you to process the data as its loaded. This gives you maximum flexibility when dealing with your download. Call GetStreamAsync and pass your own stream processor as the first argument. This delegate will get called on a background thread with a Stream which allows you to perform latency intensive operations or calculations such as storing the contents to disk.

// Create a reference to the file you want to download
Firebase.Storage.StorageReference islandRef = storage_ref.Child("images/island.jpg"];

// Download via a Stream
islandRef.GetStreamAsync( stream => {
        // Do something with the stream here.
        //
        // This code runs on a background thread which reduces the impact
        // to your framerate.
        //
        // If you want to do something on the main thread, you can do that in the
        // progress eventhandler (second argument) or ContinueWith to execute it
        // at task completion.
    }, null, CancellationToken.None);

GetStreamAsync() takes an optional arguments after the stream processor that allows you to cancel the operation or get notified of progress.

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 in a different app.

// Create a reference to the file you want to download
Firebase.Storage.StorageReference islandRef = storage_ref.Child("images/island.jpg"];

// Create local filesystem URL
string local_url = "file:///local/images/island.jpg";

// Download to the local filesystem
islandRef.GetFileAsync(local_url).ContinueWith(task => {
        if (!task.IsFaulted && !task.IsCancelled) {
            DebugLog("File downloaded.");
        }
    });

GetFileAsync() takes an optional IProgress<DownloadState> argument which you can use to monitor your download. See Manage Downloads for more information.

Generate a download URL

If you already have download infrastructure based around URLs, or just want a URL to share, you can get the download URL for a file by calling the GetDownloadUrlAsync() method on a storage reference.

// Create a reference to the file you want to download
Firebase.Storage.StorageReference stars_ref = storage_ref.Child("images/stars.jpg");

// Fetch the download URL
stars_ref.GetDownloadUrlAsync().ContinueWith(task => {
        if (!task.IsFaulted && !task.IsCancelled) {
            DebugLog("Download URL: " + future.Result());
            // ... now download the file via WWW or UnityWebRequest.
        }
    });

Monitor Download Progress

You can attach listeners to downloads in order to monitor the progress of the download. 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 downloading a file
var task = storage_ref.Child("images/mountains.jpg").GetFile(
  local_file, new StorageProgress(state => {
    // called periodically during the download
    DebugLog(String.Format("Progress: {0} of {1} bytes transferred.",
                           state.BytesTransferred, state.TotalByteCount));
  }), CancellationToken.None);
task.ContinueWith(resultTask => {
        if (!resultTask.IsFaulted && !resultTask.IsCancelled) {
            DebugLog("Download finished.");
        }
    });

Handle Errors

There are a number of reasons why errors may occur on download, including the file not existing, or the user not having permission to access the desired file. More information on errors can be found in the Handle Errors section of the docs.

Next Steps

You can also get and update metadata for files that are stored in Cloud Storage.

Send feedback about...

Need help? Visit our support page.