@firebase/storage

  • Version 0.8.1
  • Published
  • 1.56 MB
  • 4 dependencies
  • Apache-2.0 license

Install

npm i @firebase/storage
yarn add @firebase/storage
pnpm add @firebase/storage

Overview

Cloud Storage for Firebase

Index

Variables

variable StringFormat

const StringFormat: {
readonly RAW: 'raw';
readonly BASE64: 'base64';
readonly BASE64URL: 'base64url';
readonly DATA_URL: 'data_url';
};
  • An enumeration of the possible string formats for upload.

    Modifiers

    • @public

Functions

function connectStorageEmulator

connectStorageEmulator: (
storage: FirebaseStorage,
host: string,
port: number,
options?: { mockUserToken?: EmulatorMockTokenOptions | string }
) => void;
  • Modify this FirebaseStorage instance to communicate with the Cloud Storage emulator.

    Parameter storage

    The FirebaseStorage instance

    Parameter host

    The emulator host (ex: localhost)

    Parameter port

    The emulator port (ex: 5001)

    Parameter

    options.mockUserToken - the mock auth token to use for unit testing Security Rules.

    Modifiers

    • @public

function deleteObject

deleteObject: (ref: StorageReference) => Promise<void>;
  • Deletes the object at this location.

    Parameter ref

    StorageReference for object to delete.

    Returns

    A Promise that resolves if the deletion succeeds.

    Modifiers

    • @public

function getDownloadURL

getDownloadURL: (ref: StorageReference) => Promise<string>;
  • Returns the download URL for the given StorageReference.

    Parameter ref

    StorageReference to get the download URL for.

    Returns

    A Promise that resolves with the download URL for this object.

    Modifiers

    • @public

function getMetadata

getMetadata: (ref: StorageReference) => Promise<FullMetadata>;
  • A Promise that resolves with the metadata for this object. If this object doesn't exist or metadata cannot be retreived, the promise is rejected.

    Parameter ref

    StorageReference to get metadata from.

    Modifiers

    • @public

function getStorage

getStorage: (app?: any, bucketUrl?: string) => FirebaseStorage;
  • Gets a FirebaseStorage instance for the given Firebase app.

    Parameter app

    Firebase app to get FirebaseStorage instance for.

    Parameter bucketUrl

    The gs:// url to your Firebase Storage Bucket. If not passed, uses the app's default Storage Bucket.

    Returns

    A FirebaseStorage instance.

    Modifiers

    • @public

function list

list: (ref: StorageReference, options?: ListOptions) => Promise<ListResult>;
  • List items (files) and prefixes (folders) under this storage reference.

    List API is only available for Firebase Rules Version 2.

    GCS is a key-blob store. Firebase Storage imposes the semantic of '/' delimited folder structure. Refer to GCS's List API if you want to learn more.

    To adhere to Firebase Rules's Semantics, Firebase Storage does not support objects whose paths end with "/" or contain two consecutive "/"s. Firebase Storage List API will filter these unsupported objects. list() may fail if there are too many unsupported objects in the bucket.

    Parameter ref

    StorageReference to get list from.

    Parameter options

    See ListOptions for details.

    Returns

    A Promise that resolves with the items and prefixes. prefixes contains references to sub-folders and items contains references to objects in this folder. nextPageToken can be used to get the rest of the results.

    Modifiers

    • @public

function listAll

listAll: (ref: StorageReference) => Promise<ListResult>;
  • List all items (files) and prefixes (folders) under this storage reference.

    This is a helper method for calling list() repeatedly until there are no more results. The default pagination size is 1000.

    Note: The results may not be consistent if objects are changed while this operation is running.

    Warning: listAll may potentially consume too many resources if there are too many results.

    Parameter ref

    StorageReference to get list from.

    Returns

    A Promise that resolves with all the items and prefixes under the current storage reference. prefixes contains references to sub-directories and items contains references to objects in this folder. nextPageToken is never returned.

    Modifiers

    • @public

function ref

ref: {
(storage: FirebaseStorage, url?: string): StorageReference;
(
storageOrRef: FirebaseStorage | StorageReference,
path?: string
): StorageReference;
};

function updateMetadata

updateMetadata: (
ref: StorageReference,
metadata: SettableMetadata
) => Promise<FullMetadata>;
  • Updates the metadata for this object.

    Parameter ref

    StorageReference to update metadata for.

    Parameter metadata

    The new metadata for the object. Only values that have been explicitly set will be changed. Explicitly setting a value to null will remove the metadata.

    Returns

    A Promise that resolves with the new metadata for this object.

    Modifiers

    • @public

function uploadBytes

uploadBytes: (
ref: StorageReference,
data: Blob | Uint8Array | ArrayBuffer,
metadata?: UploadMetadata
) => Promise<UploadResult>;
  • Uploads data to this object's location. The upload is not resumable.

    Parameter ref

    StorageReference where data should be uploaded.

    Parameter data

    The data to upload.

    Parameter metadata

    Metadata for the data to upload.

    Returns

    A Promise containing an UploadResult

    Modifiers

    • @public

function uploadBytesResumable

uploadBytesResumable: (
ref: StorageReference,
data: Blob | Uint8Array | ArrayBuffer,
metadata?: UploadMetadata
) => UploadTask;
  • Uploads data to this object's location. The upload can be paused and resumed, and exposes progress updates.

    Parameter ref

    StorageReference where data should be uploaded.

    Parameter data

    The data to upload.

    Parameter metadata

    Metadata for the data to upload.

    Returns

    An UploadTask

    Modifiers

    • @public

function uploadString

uploadString: (
ref: StorageReference,
value: string,
format?: string,
metadata?: UploadMetadata
) => Promise<UploadResult>;
  • Uploads a string to this object's location. The upload is not resumable.

    Parameter ref

    StorageReference where string should be uploaded.

    Parameter value

    The string to upload.

    Parameter format

    The format of the string to upload.

    Parameter metadata

    Metadata for the string to upload.

    Returns

    A Promise containing an UploadResult

    Modifiers

    • @public

Interfaces

interface FirebaseStorage

interface FirebaseStorage {}
  • A Firebase Storage instance.

    Modifiers

    • @public

property app

readonly app: FirebaseApp;

property maxOperationRetryTime

maxOperationRetryTime: number;
  • The maximum time to retry operations other than uploads or downloads in milliseconds.

property maxUploadRetryTime

maxUploadRetryTime: number;
  • The maximum time to retry uploads in milliseconds.

interface FullMetadata

interface FullMetadata extends UploadMetadata {}
  • The full set of object metadata, including read-only properties.

    Modifiers

    • @public

property bucket

bucket: string;
  • The bucket this object is contained in.

property downloadTokens

downloadTokens: string[] | undefined;
  • Tokens to allow access to the downloatd URL.

property fullPath

fullPath: string;
  • The full path of this object.

property generation

generation: string;

property metageneration

metageneration: string;

property name

name: string;
  • The short name of this object, which is the last component of the full path. For example, if fullPath is 'full/path/image.png', name is 'image.png'.

property ref

ref?: StorageReference | undefined;
  • StorageReference associated with this upload.

property size

size: number;
  • The size of this object, in bytes.

property timeCreated

timeCreated: string;
  • A date string representing when this object was created.

property updated

updated: string;
  • A date string representing when this object was last updated.

interface ListOptions

interface ListOptions {}
  • The options list() accepts.

    Modifiers

    • @public

property maxResults

maxResults?: number | null;
  • If set, limits the total number of prefixes and items to return. The default and maximum maxResults is 1000.

property pageToken

pageToken?: string | null;
  • The nextPageToken from a previous call to list(). If provided, listing is resumed from the previous position.

interface ListResult

interface ListResult {}
  • Result returned by list().

    Modifiers

    • @public

property items

items: StorageReference[];
  • Objects in this directory. You can call getMetadata() and getDownloadUrl() on them.

property nextPageToken

nextPageToken?: string;
  • If set, there might be more results for this list. Use this token to resume the list.

property prefixes

prefixes: StorageReference[];
  • References to prefixes (sub-folders). You can call list() on them to get its contents.

    Folders are implicit based on '/' in the object paths. For example, if a bucket has two objects '/a/b/1' and '/a/b/2', list('/a') will return '/a/b' as a prefix.

interface SettableMetadata

interface SettableMetadata {}
  • Object metadata that can be set at any time.

    Modifiers

    • @public

property cacheControl

cacheControl?: string | undefined;
  • Served as the 'Cache-Control' header on object download.

property contentDisposition

contentDisposition?: string | undefined;
  • Served as the 'Content-Disposition' header on object download.

property contentEncoding

contentEncoding?: string | undefined;
  • Served as the 'Content-Encoding' header on object download.

property contentLanguage

contentLanguage?: string | undefined;
  • Served as the 'Content-Language' header on object download.

property contentType

contentType?: string | undefined;
  • Served as the 'Content-Type' header on object download.

property customMetadata

customMetadata?:
| {
[key: string]: string;
}
| undefined;
  • Additional user-defined custom metadata.

interface StorageError

interface StorageError {}
  • An error returned by the Firebase Storage SDK.

    Modifiers

    • @public

property code

code: string;

    property customData

    customData?: Record<string, unknown>;

      property message

      message: string;

        property name

        name: 'FirebaseError';

          property serverResponse

          serverResponse: string | null;
          • A server response message for the error, if applicable.

          property stack

          stack?: string;

            interface StorageObserver

            interface StorageObserver<T> {}
            • A stream observer for Firebase Storage.

              Modifiers

              • @public

            property complete

            complete?: CompleteFn | null;

              property error

              error?: (error: StorageError) => void | null;

                property next

                next?: NextFn<T> | null;

                  interface StorageReference

                  interface StorageReference {}
                  • Represents a reference to a Google Cloud Storage object. Developers can upload, download, and delete objects, as well as get/set object metadata.

                    Modifiers

                    • @public

                  property bucket

                  bucket: string;
                  • The name of the bucket containing this reference's object.

                  property fullPath

                  fullPath: string;
                  • The full path of this object.

                  property name

                  name: string;
                  • The short name of this object, which is the last component of the full path. For example, if fullPath is 'full/path/image.png', name is 'image.png'.

                  property parent

                  parent: StorageReference | null;
                  • A reference pointing to the parent location of this reference, or null if this reference is the root.

                  property root

                  root: StorageReference;
                  • A reference to the root of this object's bucket.

                  property storage

                  storage: FirebaseStorage;

                  method toString

                  toString: () => string;
                  • Returns a gs:// URL for this object in the form gs://<bucket>/<path>/<to>/<object>

                    Returns

                    The gs:// URL.

                  interface UploadMetadata

                  interface UploadMetadata extends SettableMetadata {}
                  • Object metadata that can be set at upload.

                    Modifiers

                    • @public

                  property md5Hash

                  md5Hash?: string | undefined;
                  • A Base64-encoded MD5 hash of the object being uploaded.

                  interface UploadResult

                  interface UploadResult {}
                  • Result returned from a non-resumable upload.

                    Modifiers

                    • @public

                  property metadata

                  readonly metadata: FullMetadata;
                  • Contains the metadata sent back from the server.

                  property ref

                  readonly ref: StorageReference;
                  • The reference that spawned this upload.

                  interface UploadTask

                  interface UploadTask {}
                  • Represents the process of uploading an object. Allows you to monitor and manage the upload.

                    Modifiers

                    • @public

                  property snapshot

                  snapshot: UploadTaskSnapshot;
                  • A snapshot of the current task state.

                  method cancel

                  cancel: () => boolean;
                  • Cancels a running task. Has no effect on a complete or failed task.

                    Returns

                    True if the cancel had an effect.

                  method catch

                  catch: (onRejected: (error: StorageError) => unknown) => Promise<unknown>;
                  • Equivalent to calling then(null, onRejected).

                  method on

                  on: (
                  event: TaskEvent,
                  nextOrObserver?:
                  | StorageObserver<UploadTaskSnapshot>
                  | ((snapshot: UploadTaskSnapshot) => unknown),
                  error?: (a: StorageError) => unknown,
                  complete?: Unsubscribe | null
                  ) => Unsubscribe | Subscribe<UploadTaskSnapshot>;
                  • Listens for events on this task.

                    Events have three callback functions (referred to as next, error, and complete).

                    If only the event is passed, a function that can be used to register the callbacks is returned. Otherwise, the callbacks are passed after the event.

                    Callbacks can be passed either as three separate arguments or as the next, error, and complete properties of an object. Any of the three callbacks is optional, as long as at least one is specified. In addition, when you add your callbacks, you get a function back. You can call this function to unregister the associated callbacks.

                    Parameter event

                    The type of event to listen for.

                    Parameter nextOrObserver

                    The next function, which gets called for each item in the event stream, or an observer object with some or all of these three properties (next, error, complete).

                    Parameter error

                    A function that gets called with a StorageError if the event stream ends due to an error.

                    Parameter completed

                    A function that gets called if the event stream ends normally.

                    Returns

                    If only the event argument is passed, returns a function you can use to add callbacks (see the examples above). If more than just the event argument is passed, returns a function you can call to unregister the callbacks.

                    Example 1

                    **Pass callbacks separately or in an object.**

                    var next = function(snapshot) {};
                    var error = function(error) {};
                    var complete = function() {};
                    // The first example.
                    uploadTask.on(
                    firebase.storage.TaskEvent.STATE_CHANGED,
                    next,
                    error,
                    complete);
                    // This is equivalent to the first example.
                    uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, {
                    'next': next,
                    'error': error,
                    'complete': complete
                    });
                    // This is equivalent to the first example.
                    var subscribe = uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED);
                    subscribe(next, error, complete);
                    // This is equivalent to the first example.
                    var subscribe = uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED);
                    subscribe({
                    'next': next,
                    'error': error,
                    'complete': complete
                    });

                    Example 2

                    **Any callback is optional.**

                    // Just listening for completion, this is legal.
                    uploadTask.on(
                    firebase.storage.TaskEvent.STATE_CHANGED,
                    null,
                    null,
                    function() {
                    console.log('upload complete!');
                    });
                    // Just listening for progress/state changes, this is legal.
                    uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, function(snapshot) {
                    var percent = snapshot.bytesTransferred / snapshot.totalBytes * 100;
                    console.log(percent + "% done");
                    });
                    // This is also legal.
                    uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, {
                    'complete': function() {
                    console.log('upload complete!');
                    }
                    });

                    Example 3

                    **Use the returned function to remove callbacks.**

                    var unsubscribe = uploadTask.on(
                    firebase.storage.TaskEvent.STATE_CHANGED,
                    function(snapshot) {
                    var percent = snapshot.bytesTransferred / snapshot.totalBytes * 100;
                    console.log(percent + "% done");
                    // Stop after receiving one update.
                    unsubscribe();
                    });
                    // This code is equivalent to the above.
                    var handle = uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED);
                    unsubscribe = handle(function(snapshot) {
                    var percent = snapshot.bytesTransferred / snapshot.totalBytes * 100;
                    console.log(percent + "% done");
                    // Stop after receiving one update.
                    unsubscribe();
                    });

                  method pause

                  pause: () => boolean;
                  • Pauses a currently running task. Has no effect on a paused or failed task.

                    Returns

                    True if the operation took effect, false if ignored.

                  method resume

                  resume: () => boolean;
                  • Resumes a paused task. Has no effect on a currently running or failed task.

                    Returns

                    True if the operation took effect, false if ignored.

                  method then

                  then: (
                  onFulfilled?: (snapshot: UploadTaskSnapshot) => unknown,
                  onRejected?: (error: StorageError) => unknown
                  ) => Promise<unknown>;
                  • This object behaves like a Promise, and resolves with its snapshot data when the upload completes.

                    Parameter onFulfilled

                    The fulfillment callback. Promise chaining works as normal.

                    Parameter onRejected

                    The rejection callback.

                  interface UploadTaskSnapshot

                  interface UploadTaskSnapshot {}
                  • Holds data about the current state of the upload task.

                    Modifiers

                    • @public

                  property bytesTransferred

                  bytesTransferred: number;
                  • The number of bytes that have been successfully uploaded so far.

                  property metadata

                  metadata: FullMetadata;
                  • Before the upload completes, contains the metadata sent to the server. After the upload completes, contains the metadata sent back from the server.

                  property ref

                  ref: StorageReference;
                  • The reference that spawned this snapshot's upload task.

                  property state

                  state: TaskState;
                  • The current state of the task.

                  property task

                  task: UploadTask;
                  • The task of which this is a snapshot.

                  property totalBytes

                  totalBytes: number;
                  • The total number of bytes to be uploaded.

                  Type Aliases

                  type StringFormat

                  type StringFormat = typeof StringFormat[keyof typeof StringFormat];
                  • An enumeration of the possible string formats for upload.

                    Modifiers

                    • @public

                  type TaskEvent

                  type TaskEvent = 'state_changed';
                  • An event that is triggered on a task.

                    Modifiers

                    • @public

                  type TaskState

                  type TaskState = 'running' | 'paused' | 'success' | 'canceled' | 'error';
                  • Represents the current state of a running upload.

                    Modifiers

                    • @public

                  Package Files (1)

                  Dependencies (4)

                  Dev Dependencies (7)

                  Peer Dependencies (1)

                  Badge

                  To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                  You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@firebase/storage.

                  • Markdown
                    [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@firebase/storage)
                  • HTML
                    <a href="https://www.jsdocs.io/package/@firebase/storage"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>