@firebase/storage
- Version 0.13.6
- Published
- 2.18 MB
- 3 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
Functions
Classes
Interfaces
Enums
StorageErrorCode
- APP_DELETED
- BUCKET_NOT_FOUND
- CANCELED
- CANNOT_SLICE_BLOB
- INTERNAL_ERROR
- INVALID_ARGUMENT
- INVALID_ARGUMENT_COUNT
- INVALID_CHECKSUM
- INVALID_DEFAULT_BUCKET
- INVALID_EVENT_NAME
- INVALID_FORMAT
- INVALID_ROOT_OPERATION
- INVALID_URL
- NO_DEFAULT_BUCKET
- NO_DOWNLOAD_URL
- OBJECT_NOT_FOUND
- PROJECT_NOT_FOUND
- QUOTA_EXCEEDED
- RETRY_LIMIT_EXCEEDED
- SERVER_FILE_WRONG_SIZE
- UNAUTHENTICATED
- UNAUTHORIZED
- UNAUTHORIZED_APP
- UNKNOWN
- UNSUPPORTED_ENVIRONMENT
Type Aliases
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
Emulator options.
options.mockUserToken
is 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 getBlob
getBlob: (ref: StorageReference, maxDownloadSizeBytes?: number) => Promise<Blob>;
Downloads the data at the object's location. Returns an error if the object is not found.
To use this functionality, you have to whitelist your app's origin in your Cloud Storage bucket. See also https://cloud.google.com/storage/docs/configuring-cors
This API is not available in Node.
Parameter ref
StorageReference where data should be downloaded.
Parameter maxDownloadSizeBytes
If set, the maximum allowed size in bytes to retrieve.
Returns
A Promise that resolves with a Blob containing the object's bytes
Modifiers
@public
function getBytes
getBytes: ( ref: StorageReference, maxDownloadSizeBytes?: number) => Promise<ArrayBuffer>;
Downloads the data at the object's location. Returns an error if the object is not found.
To use this functionality, you have to whitelist your app's origin in your Cloud Storage bucket. See also https://cloud.google.com/storage/docs/configuring-cors
Parameter ref
StorageReference where data should be downloaded.
Parameter maxDownloadSizeBytes
If set, the maximum allowed size in bytes to retrieve.
Returns
A Promise containing the object's bytes
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 retrieved, the promise is rejected.Parameter ref
StorageReference to get metadata from.
Modifiers
@public
function getStorage
getStorage: (app?: FirebaseApp, 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 getStream
getStream: ( ref: StorageReference, maxDownloadSizeBytes?: number) => ReadableStream;
Downloads the data at the object's location. Raises an error event if the object is not found.
This API is only available in Node.
Parameter ref
StorageReference where data should be downloaded.
Parameter maxDownloadSizeBytes
If set, the maximum allowed size in bytes to retrieve.
Returns
A stream with the object's data as bytes
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 anditems
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 anditems
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;};
Returns a StorageReference for the given url.
Parameter storage
FirebaseStorage instance.
Parameter url
URL. If empty, returns root reference.
Modifiers
@public
Returns a StorageReference for the given path in the default bucket.
Parameter storageOrRef
Parameter pathOrUrlStorage
path. If empty, returns root reference (if FirebaseStorage instance provided) or returns same reference (if StorageReference provided).
Modifiers
@public
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?: StringFormat, 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
Classes
class StorageError
class StorageError extends FirebaseError {}
An error returned by the Firebase Storage SDK.
Modifiers
@public
constructor
constructor(code: StorageErrorCode, message: string, status_?: number);
Parameter code
A
StorageErrorCode
string to be prefixed with 'storage/' and added to the end of the message.Parameter message
Error message.
Parameter status_
Corresponding HTTP Status Code
property customData
customData: { serverResponse: string | null };
Stores custom error data unique to the
StorageError
.
property serverResponse
serverResponse: string;
Optional response message that was added by the server.
property status
status: number;
Interfaces
interface FirebaseStorage
interface FirebaseStorage {}
A Firebase Storage instance.
Modifiers
@public
property app
readonly app: FirebaseApp;
The @firebase/app#FirebaseApp associated with this
FirebaseStorage
instance.
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 download URL.
property fullPath
fullPath: string;
The full path of this object.
property generation
generation: string;
The object's generation. https://cloud.google.com/storage/docs/metadata#generation-number
property metageneration
metageneration: string;
The object's metageneration. https://cloud.google.com/storage/docs/metadata#generation-number
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
anditems
to return. The default and maximum maxResults is 1000.
property pageToken
pageToken?: string | null;
The
nextPageToken
from a previous call tolist()
. 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 StorageObserver
interface StorageObserver<T> {}
A stream observer for Firebase Storage.
Modifiers
@public
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;
The FirebaseStorage instance associated with this reference.
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
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
, andcomplete
).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
, andcomplete
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.
Enums
enum StorageErrorCode
enum StorageErrorCode { UNKNOWN = 'unknown', OBJECT_NOT_FOUND = 'object-not-found', BUCKET_NOT_FOUND = 'bucket-not-found', PROJECT_NOT_FOUND = 'project-not-found', QUOTA_EXCEEDED = 'quota-exceeded', UNAUTHENTICATED = 'unauthenticated', UNAUTHORIZED = 'unauthorized', UNAUTHORIZED_APP = 'unauthorized-app', RETRY_LIMIT_EXCEEDED = 'retry-limit-exceeded', INVALID_CHECKSUM = 'invalid-checksum', CANCELED = 'canceled', INVALID_EVENT_NAME = 'invalid-event-name', INVALID_URL = 'invalid-url', INVALID_DEFAULT_BUCKET = 'invalid-default-bucket', NO_DEFAULT_BUCKET = 'no-default-bucket', CANNOT_SLICE_BLOB = 'cannot-slice-blob', SERVER_FILE_WRONG_SIZE = 'server-file-wrong-size', NO_DOWNLOAD_URL = 'no-download-url', INVALID_ARGUMENT = 'invalid-argument', INVALID_ARGUMENT_COUNT = 'invalid-argument-count', APP_DELETED = 'app-deleted', INVALID_ROOT_OPERATION = 'invalid-root-operation', INVALID_FORMAT = 'invalid-format', INTERNAL_ERROR = 'internal-error', UNSUPPORTED_ENVIRONMENT = 'unsupported-environment',}
Error codes that can be attached to
StorageError
objects.Modifiers
@public
member APP_DELETED
APP_DELETED = 'app-deleted'
member BUCKET_NOT_FOUND
BUCKET_NOT_FOUND = 'bucket-not-found'
member CANCELED
CANCELED = 'canceled'
member CANNOT_SLICE_BLOB
CANNOT_SLICE_BLOB = 'cannot-slice-blob'
member INTERNAL_ERROR
INTERNAL_ERROR = 'internal-error'
member INVALID_ARGUMENT
INVALID_ARGUMENT = 'invalid-argument'
member INVALID_ARGUMENT_COUNT
INVALID_ARGUMENT_COUNT = 'invalid-argument-count'
member INVALID_CHECKSUM
INVALID_CHECKSUM = 'invalid-checksum'
member INVALID_DEFAULT_BUCKET
INVALID_DEFAULT_BUCKET = 'invalid-default-bucket'
member INVALID_EVENT_NAME
INVALID_EVENT_NAME = 'invalid-event-name'
member INVALID_FORMAT
INVALID_FORMAT = 'invalid-format'
member INVALID_ROOT_OPERATION
INVALID_ROOT_OPERATION = 'invalid-root-operation'
member INVALID_URL
INVALID_URL = 'invalid-url'
member NO_DEFAULT_BUCKET
NO_DEFAULT_BUCKET = 'no-default-bucket'
member NO_DOWNLOAD_URL
NO_DOWNLOAD_URL = 'no-download-url'
member OBJECT_NOT_FOUND
OBJECT_NOT_FOUND = 'object-not-found'
member PROJECT_NOT_FOUND
PROJECT_NOT_FOUND = 'project-not-found'
member QUOTA_EXCEEDED
QUOTA_EXCEEDED = 'quota-exceeded'
member RETRY_LIMIT_EXCEEDED
RETRY_LIMIT_EXCEEDED = 'retry-limit-exceeded'
member SERVER_FILE_WRONG_SIZE
SERVER_FILE_WRONG_SIZE = 'server-file-wrong-size'
member UNAUTHENTICATED
UNAUTHENTICATED = 'unauthenticated'
member UNAUTHORIZED
UNAUTHORIZED = 'unauthorized'
member UNAUTHORIZED_APP
UNAUTHORIZED_APP = 'unauthorized-app'
member UNKNOWN
UNKNOWN = 'unknown'
member UNSUPPORTED_ENVIRONMENT
UNSUPPORTED_ENVIRONMENT = 'unsupported-environment'
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 (3)
Dev Dependencies (7)
Peer Dependencies (1)
Badge
To add a badge like this oneto 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[](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>
- Updated .
Package analyzed in 4791 ms. - Missing or incorrect documentation? Open an issue for this package.