This plugin allows you to use the native Firebase SDKs for Cloud Storage in your Nativescript app.
To use Firebase Cloud Storage, you initialize Firebase first. To set up and initialize Firebase for your NativeScript app, follow the instructions on the documentation of the @nativescript/firebase-core plugin.
To create a default Cloud Storage bucket, follow the instructions at Create a default Cloud Storage bucket.
To add the Cloud Storage SDK to your app, install and import the @nativescript/firebase-storage
plugin.
npm install @nativescript/firebase-storage
@nativescript/firebase-storage
plugin. You should import the plugin once in your app project and the ideal place to do that is the app bootstrapping file( app.ts
, main.ts
, etc).To create a new Storage instance, call the instance getter, storage()
, method on the FirebaseApp instance.:
import { firebase } from '@nativescript/firebase-core'
const storage = firebase().storage()
By default, this allows you to interact with Firebase Storage using the default Firebase App used whilst installing Firebase on your platform. However, if you'd like to use a secondary Firebase App, pass the secondary app instance when calling the storage
method:
import { firebase } from '@nativescript/firebase-core'
import '@nativescript/firebase-storage'
// create secondary app instance
const config = new FirebaseOptions()
const secondaryApp = firebase.initializeApp(config, 'SECONDARY_APP')
const storage = firebase().storage(secondaryApp)
You can view your buckets on the Firebase Console.
A reference is a local pointer to some file on your bucket. This can either be a file that already exists or one which does not exist yet.
import { firebase } from '@nativescript/firebase-core'
import '@nativescript/firebase-storage'
const reference = firebase().storage().ref('black-t-shirt-sm.png')
import { firebase } from '@nativescript/firebase-core'
const reference = firebase().storage().ref('/images/t-shirts/black-t-shirt-sm.png')
To upload a file directly from the user's device, follow these steps:
import { firebase } from '@nativescript/firebase-core'
const reference = firebase().storage().ref('black-t-shirt-sm.png')
-2. Get the path to the file on the users device. For example,
import { knownfolders } from '@nativescript/core'
const pathToFile = knownFolders.documents().getFile('black-t-shirt-sm.png')
const filePath = pathToFile.path
await reference.putFile(filePath)
The putFile method in the preceding example returns a Task object, that allows you to hook into information such as the current upload progress.
To check the current task progress, you can listen to the state_changed
event on the task:
const task = reference.putFile(pathToFile)
task.on('state_changed', taskSnapshot => {
console.log(
`${taskSnapshot.bytesTransferred} transferred out of ${taskSnapshot.totalBytes}`
)
})
task.then(() => {
console.log('Image uploaded to the bucket!')
})
A task also provides the ability to pause and resume ongoing operations. To pause a task, call the pause method and to resume, call the resume method:
const task = reference.putFile(pathToFile)
task.pause()
// Sometime later...
task.resume()
A common use case for Cloud Storage is to use it as a global Content Delivery Network (CDN) for your images. When uploading files to a bucket, they are not automatically available for consumption via an HTTP URL. To generate a new Download URL, you need to call the getDownloadURL
method on a reference:
import { firebase } from '@nativescript/firebase-core'
const url = firebase().storage().ref('images/profile-1.png').getDownloadURL()
To view a full list of the current files & directories within a particular bucket reference, call list on a reference instance. The results are paginated, and if more results are available you can pass a page token into the request:
import { firebase } from '@nativescript/firebase-core'
function listFilesAndDirectories(reference, pageToken) {
return reference.list({ pageToken }).then(result => {
// Loop over each item
result.items.forEach(ref => {
console.log(ref.fullPath)
})
if (result.nextPageToken) {
return listFilesAndDirectories(reference, result.nextPageToken)
}
return Promise.resolve()
})
}
const reference = firebase().storage().ref('images')
listFilesAndDirectories(reference).then(() => {
console.log('Finished listing')
})
By default your bucket will come with rules which allow only authenticated users on your project to access it. You can, however, fully customize the security rules to your application's requirements.
To learn more, see Get started with Firebase Security Rules documentation on the Firebase website.
A single Firebase project can have multiple storage buckets. The module will use the default bucket if no bucket argument is passed to the storage instance. To switch buckets, provide the module with the gs:// bucket URL found on the Firebase Console, under Storage > Files
.
import { firebase, FirebaseOptions } from '@nativescript/firebase-core'
const defaultStorageBucket = firebase().storage()
const config = new FirebaseOptions()
config.storageBucket = 'gs://my-secondary-bucket.appspot.com'
const secondaryApp = firebase.app(config, 'SECONDARY_APP')
const secondaryStorageBucket = firebase().storage(secondaryApp)
import { firebase } from '@nativescript/firebase-core'
storageAndroid: com.google.firebase.storage.FirebaseStorage = firebase().storage().android
A read-only
property that returns the underlying native Android object.
import { firebase } from '@nativescript/firebase-core'
storageIOS: FIRStorage = firebase().storage().ios
A read-only
property that returns the underlying native iOS object.
import { firebase } from '@nativescript/firebase-core'
storageApp: FirebaseApp = firebase().storage().app
A read-only
property that returns the FirebaseApp instance to which this Storage belongs.
import { firebase } from '@nativescript/firebase-core'
maxDownloadRetryTime: number = firebase().storage().maxDownloadRetryTime
// or
Returns or sets the maximum time, in milliseconds, to retry downloads in the case of a failure.
import { firebase } from '@nativescript/firebase-core'
maxOperationRetryTime: number = firebase().storage().maxOperationRetryTime
Returns or sets the maximum time, in milliseconds, to retry operations other than uploads or downloads in the case of a failure.
import { firebase } from '@nativescript/firebase-core'
maxUploadRetryTime: number = firebase().storage().maxUploadRetryTime
Gets or sets the maximum time, in milliseconds, to retry uploads in the case of a failure.
import { firebase } from '@nativescript/firebase-core'
new Storage(app)
Parameter | Type | Description |
---|---|---|
app | FirebaseApp | Optional : The FirebaseApp instance to which this Storage belongs. |
import { firebase } from '@nativescript/firebase-core'
firebase().storage().useEmulator(host, port)
Attempts to connect to the Storage emulator running locally on the given host and port.
Parameter | Type | Description |
---|---|---|
host | string | The emulator host. |
port | number | The emulator port. |
import { firebase } from '@nativescript/firebase-core'
reference: Reference = firebase().storage().ref(path)
Creates a new storage reference initialized at the root Firebase Storage location, if no path argument is provided, or at the given path if a path argument is provided.
Parameter | Type | Description |
---|---|---|
path | string | Optional : The path to initialize the reference at. |
import { firebase } from '@nativescript/firebase-core'
reference: Reference = firebase().storage().refFromURL(url)
Creates a new storage reference initialized from the specific URL.
Parameter | Type | Description |
---|---|---|
url | string | The URL to initialize the reference from. |
referenceAndroid: com.google.firebase.storage.StorageReference = reference.android
A read-only
property that returns the underlying native StorageReference object for Android.
referenceIOS: FIRStorageReference = reference.ios
A read-only
property that returns the underlying native StorageReference object for iOS.
bucket: string = reference.bucket
A read-only
property that returns the name of the bucket containing this reference's object.
fullPath: string = reference.fullPath
A read-only
property that returns the full path to this object, not including the Google Cloud Storage bucket.
name: string = reference.name
A read-only
property that returns the short name of this object's path, which is the last component of the full path.
parent: Reference = reference.parent
A read-only
property that returns a reference to the parent of the current reference, or null if the current reference is the root.
root: Reference = reference.root
A read-only
property that returns a reference to the root of the current reference's bucket.
storage: Storage = reference.storage
A read-only
property that returns the Storage instance associated with the reference.
reference: Reference = reference.child(path)
Returns a reference to a relative path from the current reference. For more information, see child on the Firebase website.
Parameter | Type | Description |
---|---|---|
path | string | The child path. |
reference.delete()
Deletes the object at the current reference's location.
downloadURL: string = await reference.getDownloadURL()
Asynchronously retrieves a long-lived download URL with a revokable token. For more information, see getDownloadUrl on the Firebase website.
metadata: Metadata = await reference.getMetadata()
Asynchronously retrieves metadata associated with an object at the current reference's location. For more information description about this method, see getMetadata on the Firebase website.
You can find the properties of the Metadata object here.
listResult: ListResult = await reference.list(options)
Returns items (files) and prefixes (folders) under this StorageReference.
Parameter | Type | Description |
---|---|---|
options | ListOptions | Optional : An object to configure the listing operation. The ListOptions properties are described in the list method on the Firebase docs. |
interface ListOptions {
maxResults: undefined | number
pageToken: undefined | string
}
listResult: ListResult = await reference.listAll()
Asynchronously returns a list of all items (files) and prefixes (folders) under this StorageReference. For more information, see listAll on the Firebase website.
task: Task = reference.put(data, metadata)
Uploads data to this reference's location. For more information, see putBytes on the Firebase website.
Parameter | Type | Description |
---|---|---|
data | Blob | Uint8Array | ArrayBuffer | The data to upload. |
metadata | Metadata | Optional : The metadata to associate with this upload. |
stringTask: Task = reference.putString(data, format, metadata)
Uploads bytes data from a string to this reference's location.
Parameter | Type | Description |
---|---|---|
data | string | The base64 string to upload . |
format | StringFormat | The format of the string to upload. |
metadata | Metadata | Optional : The metadata to associate with this upload. |
enum StringFormat {
RAW = 'raw',
BASE64 = 'base64',
BASE64URL = 'base64url',
DATA_URL = 'data_url'
}
fileTask: Task = reference.putFile(path, metadata)
Uploads a file to this reference's location.
Parameter | Type | Description |
---|---|---|
path | string | The path to the file to upload. |
metadata | Metadata | Optional : The metadata to associate with this upload. |
updatedMetadata: FullMetadata = await reference.updateMetadata(metadata)
Updates the specified metadata associated with this reference. For more information, see updateMetadata on the Firebase website.
Parameter | Type | Description |
---|---|---|
metadata | Metadata | The metadata to update. |
fileWriteTask: Task = reference.writeToFile(localFilePath)
Downloads the object at this reference's location to the specified system file path. For more information, see writeToFile on the Firebase website.
Parameter | Type | Description |
---|---|---|
localFilePath | string | The path to which the file should be downloaded. |
taskAndroid: com.google.firebase.storage.FileDownloadTask.TaskSnapshot | com.google.firebase.storage.UploadTask.TaskSnapshot = task.android;
A read-only
property that returns the native Android object.
taskIOS: FIRStorageUploadTask | FIRStorageDownloadTask = task.ios;
A read-only
property that returns the native iOS object.
taskSnapshot: TaskSnapshot = task.snapshot
task.on(event, nextOrObserver, error, complete)
Parameter | Type | Description |
---|---|---|
event | TaskEvent | The event name. |
nextOrObserver | ((a: TaskSnapshot) => any) | TaskSnapshotObserver | Optional : The observer object or a function to be called on each event. |
error | (a: FirebaseError) => any | Optional : The function to be called on error. |
complete | () => void | Optional : The function to be called on completion. |
enum TaskEvent {
STATE_CHANGED = 'state_changed'
}
cancelled: boolean = task.cancel()
Cancels the current upload or download task.
paused: boolean = task.pause()
Pauses the current upload or download task.
resumed: boolean = task.resume()
Resumes the current upload or download task.
Apache License Version 2.0