npm.io
8.6.0 • Published 3 weeks ago

@capacitor-firebase/storage

Licence
Apache-2.0
Version
8.6.0
Deps
0
Size
202 kB
Vulns
0
Weekly
0
Stars
532

Capacitor Firebase Cloud Storage Plugin

Unofficial Capacitor plugin for Firebase Cloud Storage.[^1]

Use Cases

The Firebase Cloud Storage plugin is typically used to store and serve user-generated content, for example:

  • User-generated content: Upload photos or other files created by your users to Cloud Storage.
  • File downloads: Download files to the local file system on Android and iOS or as a Blob on the Web.
  • Content delivery: Retrieve the download URL of a file to display or share it.
  • File management: List the files in a directory, read and update their metadata, or delete them.

Compatibility

Plugin Version Capacitor Version Status
8.x.x >=8.x.x Active support
7.x.x 7.x.x Deprecated
6.x.x 6.x.x Deprecated

Guides

Installation

You can use our AI-Assisted Setup to install the plugin. Add the Capawesome Skills to your AI tool using the following command:

npx skills add capawesome-team/skills --skill capacitor-plugins

Then use the following prompt:

Use the `capacitor-plugins` skill from `capawesome-team/skills` to install the `@capacitor-firebase/storage` plugin in my project.

If you prefer Manual Setup, install the plugin by running the following commands and follow the platform-specific instructions below:

npm install @capacitor-firebase/storage
npx cap sync

Add Firebase to your project if you haven't already (Android / iOS).

Android
Variables

If needed, you can define the following project variable in your app’s variables.gradle file to change the default version of the dependency:

  • $firebaseStorageVersion version of com.google.firebase:firebase-storage (default: 22.0.1)

This can be useful if you encounter dependency conflicts with other plugins in your project.

iOS
Swift Package Manager

Add the following to your capacitor.config.json (or capacitor.config.ts) to avoid a SwiftPM package identity collision:

{
  "experimental": {
    "ios": {
      "spm": {
        "packageOptions": {
          "@capacitor-firebase/storage": {
            "symlink": true
          }
        }
      }
    }
  }
}

Attention: SPM packageOptions support requires Capacitor CLI 8.4.0+.

Configuration

No configuration required for this plugin.

Demo

A working example can be found here: robingenz/capacitor-firebase-plugin-demo

Starter templates

The following starter templates are available:

Usage

The following examples show how to upload and download files, get a download URL, list files, read and update file metadata, delete files, and connect to the Cloud Storage emulator.

Upload a file

Upload a file to Cloud Storage. On Android and iOS, provide the uri to the file to upload. On the Web, provide the data to upload as a Blob using the blob option instead. The callback is invoked with the upload progress and with completed set to true once the upload is finished:

import { FirebaseStorage } from '@capacitor-firebase/storage';

const uploadFile = async () => {
  return new Promise((resolve, reject) => {
    FirebaseStorage.uploadFile(
      {
        path: 'images/mountains.png',
        uri: 'file:///var/mobile/Containers/Data/Application/E397A70D-67E4-4258-236E-W1D9E12111D4/Library/Caches/092F8464-DE60-40B3-8A23-EB83160D9F9F/mountains.png',
      },
      (event, error) => {
        if (error) {
          reject(error);
        } else if (event?.completed) {
          resolve();
        }
      }
    );
  });
};
Download a file

Download a file from Cloud Storage. On Android and iOS, the file is downloaded to the local file system using the uri option. On the Web, the downloaded file is returned as a Blob in the callback event:

import { FirebaseStorage } from '@capacitor-firebase/storage';

const downloadFileWithFirebaseStorage = async () => {
  return new Promise((resolve, reject) => {
    FirebaseStorage.downloadFile(
      {
        path: 'images/mountains.png',
        uri: 'file:///var/mobile/Containers/Data/Application/E397A70D-67E4-4258-236E-W1D9E12111D4/Library/Caches/mountains.png', // Only available for Android and iOS
      },
      (event, error) => {
        if (error) {
          reject(error);
        } else if (event?.completed) {
          // On Web, the downloaded file is available as a Blob in event.blob
          resolve(event?.blob);
        }
      }
    );
  });
};
Download a file with the Filesystem plugin

Alternatively, you can retrieve the download URL of the file and download it using the official Capacitor Filesystem plugin:

import { FirebaseStorage } from '@capacitor-firebase/storage';
import { Filesystem, Directory } from '@capacitor/filesystem';

const downloadFileWithFilesystem = async () => {
  const { downloadUrl } = await FirebaseStorage.getDownloadUrl({
    path: 'images/mountains.png',
  });
  const { path } = await Filesystem.downloadFile({
    url: downloadUrl,
    path: 'mountains.png',
    directory: Directory.Cache,
  });
  return path;
};
Get a download URL

Retrieve the download URL of a file, for example to display or share it:

import { FirebaseStorage } from '@capacitor-firebase/storage';

const getDownloadUrl = async () => {
  const { downloadUrl } = await FirebaseStorage.getDownloadUrl({
    path: 'images/mountains.png',
  });
  return downloadUrl;
};
List files in a directory

List the files in a directory. Use the maxResults and pageToken options to paginate through large directories:

import { FirebaseStorage } from '@capacitor-firebase/storage';

const listFiles = async () => {
  const { items } = await FirebaseStorage.listFiles({
    path: 'images',
  });
  return items;
};
Read and update file metadata

Read the metadata of a file, such as its size, content type, and timestamps, or update it, including user-defined custom metadata:

import { FirebaseStorage } from '@capacitor-firebase/storage';

const getMetadata = async () => {
  const result = await FirebaseStorage.getMetadata({
    path: 'images/mountains.png',
  });
  return result;
};

const updateMetadata = async () => {
  await FirebaseStorage.updateMetadata({
    path: 'images/mountains.png',
    metadata: {
      contentType: 'image/png',
      customMetadata: {
        foo: 'bar',
      },
    },
  });
};
Delete a file

Delete a file from Cloud Storage:

import { FirebaseStorage } from '@capacitor-firebase/storage';

const deleteFile = async () => {
  await FirebaseStorage.deleteFile({
    path: 'images/mountains.png',
  });
};
Use the Cloud Storage emulator

During development, you can instrument your app to talk to the local Cloud Storage emulator. When using an Android emulator device, 10.0.2.2 is the special IP address to connect to the localhost of the host computer. Note that on Android, the cleartext traffic must be allowed, which is not intended for use in production:

import { FirebaseStorage } from '@capacitor-firebase/storage';

const useEmulator = async () => {
  await FirebaseStorage.useEmulator({
    host: '10.0.2.2',
    port: 9001,
  });
};

API

deleteFile(...)
deleteFile(options: DeleteFileOptions) => Promise<void>

Delete a file.

Param Type
options DeleteFileOptions

Since: 5.3.0


getDownloadUrl(...)
getDownloadUrl(options: GetDownloadUrlOptions) => Promise<GetDownloadUrlResult>

Get the download url for a file.

Param Type
options GetDownloadUrlOptions

Returns: Promise<GetDownloadUrlResult>

Since: 5.3.0


getMetadata(...)
getMetadata(options: GetMetadataOptions) => Promise<GetMetadataResult>

Get the metadata for a file.

Param Type
options GetMetadataOptions

Returns: Promise<GetMetadataResult>

Since: 5.3.0


listFiles(...)
listFiles(options: ListFilesOptions) => Promise<ListFilesResult>

List files in a directory.

Param Type
options ListFilesOptions

Returns: Promise<ListFilesResult>

Since: 5.3.0


updateMetadata(...)
updateMetadata(options: UpdateMetadataOptions) => Promise<void>

Update the metadata for a file.

Param Type
options UpdateMetadataOptions

Since: 5.3.0


downloadFile(...)
downloadFile(options: DownloadFileOptions, callback: DownloadFileCallback) => Promise<CallbackId>

Download a file.

On Android and iOS, the file is downloaded to the local file system using the uri option.

On Web, the file is downloaded as a Blob and returned in the callback event.

Param Type
options DownloadFileOptions
callback DownloadFileCallback

Returns: Promise<string>

Since: 8.2.0


uploadFile(...)
uploadFile(options: UploadFileOptions, callback: UploadFileCallback) => Promise<CallbackId>

Upload a file.

Param Type
options UploadFileOptions
callback UploadFileCallback

Returns: Promise<string>

Since: 5.3.0


useEmulator(...)
useEmulator(options: UseEmulatorOptions) => Promise<void>

Instrument your app to talk to the Cloud Storage emulator.

On Android, the cleartext traffic must be allowed. On the Capacitor configuration:

{
  server: {
    cleartext: true
  }
}

The cleartext traffic is not intended for use in production.

Param Type
options UseEmulatorOptions

Since: 6.1.0


Interfaces
DeleteFileOptions
Prop Type Description Since
path string The full path to the file to delete, including the file name. 5.3.0
GetDownloadUrlResult
Prop Type Description Since
downloadUrl string The download url for the file. 5.3.0
GetDownloadUrlOptions
Prop Type Description Since
path string The full path to the file to get the download url for, including the file name. 5.3.0
GetMetadataResult
Prop Type Description Since
bucket string The bucket this file is contained in. 5.3.0
createdAt number The timestamp at which the file was created in milliseconds since the epoch. 5.3.0
generation string The object's generation. 5.3.0
md5Hash string The md5 hash of the file. 5.3.0
metadataGeneration string The object's metadata generation. 5.3.0
name string The short name of this file, which is the last component of the full path. 5.3.0
path string The full path to the file, including the file name. 5.3.0
size number The size of the file in bytes. 5.3.0
updatedAt number The timestamp at which the file was last updated in milliseconds since the epoch. 5.3.0
cacheControl string Served as the Cache-Control header on object download. 6.1.0
contentDisposition string Served as the Content-Disposition header on object download. 6.1.0
contentEncoding string Served as the Content-Encoding header on object download. 6.1.0
contentLanguage string Served as the Content-Language header on object download. 6.1.0
contentType string Served as the Content-Type header on object download. 6.1.0
customMetadata { [key: string]: string; } Additional user-defined custom metadata. 6.1.0
GetMetadataOptions
Prop Type Description Since
path string The full path to the file to get the metadata for, including the file name. 5.3.0
ListFilesResult
Prop Type Description Since
items StorageReference[] The list of files in the directory. 5.3.0
nextPageToken string If set, there might be more results for this list. Use this token to resume the list. 5.3.0
StorageReference
Prop Type Description Since
bucket string The bucket this file is contained in. 5.3.0
path string The full path to the file, including the file name. 5.3.0
name string The short name of this file, which is the last component of the full path. 5.3.0
ListFilesOptions
Prop Type Description Default Since
path string The full path to the directory to list files for. 5.3.0
maxResults number The maximum number of results to return. 1000 5.3.0
pageToken string The page token, returned by a previous call to this method. If provided, listing is resumed from the previous position. 5.3.0
UpdateMetadataOptions
Prop Type Description Since
path string The full path to the file to update the metadata for, including the file name. 5.3.0
metadata SettableMetadata The metadata to update. 5.3.0
SettableMetadata
Prop Type Description Since
cacheControl string Served as the Cache-Control header on object download. 5.3.0
contentDisposition string Served as the Content-Disposition header on object download. 5.3.0
contentEncoding string Served as the Content-Encoding header on object download. 5.3.0
contentLanguage string Served as the Content-Language header on object download. 5.3.0
contentType string Served as the Content-Type header on object download. 5.3.0
customMetadata { [key: string]: string; } Additional user-defined custom metadata. 5.3.0
DownloadFileOptions
Prop Type Description Since
path string The full path to the file to download, including the file name. 8.2.0
uri string The uri to download the file to. Only available for Android and iOS. 8.2.0
DownloadFileCallbackEvent
Prop Type Description Since
progress number The download progress, as a percentage between 0 and 1. 8.2.0
bytesTransferred number The number of bytes that have been transferred. Only available for Android and Web. 8.2.0
totalBytes number The total number of bytes to be transferred. Only available for Android and Web. 8.2.0
completed boolean Whether the download is completed or not. 8.2.0
blob Blob The downloaded file as a Blob. Only available for Web. 8.2.0
UploadFileOptions
Prop Type Description Since
blob Blob The data to upload. Only available for Web. 5.3.0
path string The full path where data should be uploaded, including the file name. 5.3.0
uri string The uri to the file to upload. Only available for Android and iOS. 5.3.0
metadata UploadMetadata The metadata to set for the file. 5.4.0
UploadMetadata
Prop Type Description Since
md5Hash string The base64-encoded MD5 hash of the file. Only available for Web. 5.4.0
UploadFileCallbackEvent
Prop Type Description Since
progress number The upload progress, as a percentage between 0 and 1. 5.3.0
bytesTransferred number The number of bytes that have been transferred. Only available for Android and Web. 5.3.0
totalBytes number The total number of bytes to be transferred. Only available for Android and Web. 5.3.0
completed boolean Whether the upload is completed or not. 5.3.0
UseEmulatorOptions
Prop Type Description Default Since
host string The emulator host without any port or scheme. Note when using a Android Emulator device: 10.0.2.2 is the special IP address to connect to the 'localhost' of the host computer. 6.1.0
port number The emulator port. 9199 6.1.0
Type Aliases
DownloadFileCallback

(event: DownloadFileCallbackEvent | null, error: any): void

CallbackId

string

UploadFileCallback

(event: UploadFileCallbackEvent | null, error: any): void

FAQ

How do I track the progress of an upload or download?

The uploadFile(...) and downloadFile(...) methods accept a callback that is invoked with events containing the progress as a fraction between 0 and 1 and a completed flag. The bytesTransferred and totalBytes properties are only available on Android and Web.

How does downloading a file differ between the platforms?

On Android and iOS, the file is downloaded to the local file system using the uri option. On the Web, the downloaded file is returned as a Blob in the callback event. Alternatively, you can retrieve the download URL with getDownloadUrl(...) and download the file with the official Capacitor Filesystem plugin, as shown in the usage example above.

How do I upload a file selected by the user?

On Android and iOS, pass the uri of the file to the uploadFile(...) method. On the Web, pass the data as a Blob using the blob option instead. You can use the File Picker plugin to let the user select a file on the device.

How can I store additional information about a file?

You can set metadata for a file when uploading it using the metadata option or update it later with updateMetadata(...), including user-defined key-value pairs via customMetadata. Use getMetadata(...) to read the metadata of a file, such as its size, content type, and timestamps.

Can I test against the Cloud Storage emulator?

Yes, use the useEmulator(...) method to instrument your app to talk to the local Cloud Storage emulator, as shown in the usage example above. When testing on an Android emulator device, use 10.0.2.2 as the host to reach the localhost of the host computer. Keep in mind that on Android, the cleartext traffic must be allowed for this, which is not intended for use in production.

Newsletter

Stay up to date with the latest news and updates about the Capawesome, Capacitor, and Ionic ecosystem by subscribing to our Capawesome Newsletter.

Changelog

See CHANGELOG.md.

License

See LICENSE.

[^1]: This project is not affiliated with, endorsed by, sponsored by, or approved by Google LLC or any of their affiliates or subsidiaries.

Keywords