-
Notifications
You must be signed in to change notification settings - Fork 16
E.3 Upload Files
Firebase Storage allows developers to quickly and easily upload files to a Google Cloud Storage bucket provided and managed by Firebase.
Note: By default, Firebase Storage buckets require Firebase Authentication to upload files. You can change your Firebase Storage Security Rules to allow unauthenticated access. Since the default Google App Engine app and Firebase share this bucket, configuring public access may make newly uploaded App Engine files publicly accessible as well. Be sure to restrict access to your Storage bucket again when you set up authentication.
To upload a file to Firebase Storage, you first create a reference to the full path of the file, including the file name.
var rootRef:StorageReference = Storage.getReference();
// Create a reference to 'images/mountains.jpg'
var mountainImagesRef:StorageReference = rootRef.child("images/mountains.jpg");
Once you've created an appropriate reference, you then call the putBytes() or putFile() method to upload the file to Firebase Storage.
You cannot upload data with a reference to the root of your Google Cloud Storage bucket. Your reference must point to a child URL.
The putBytes()
method is the simplest way to upload a file to Firebase Storage. putBytes()
takes a ByteArray
and returns an UploadTask that you can use to manage and monitor the status of the upload.
// Let's first load "myMountains.jpg" to have access to its ByteArray data
var file:File = File.applicationDirectory.resolvePath("myMountains.jpg");
file.addEventListener(Event.COMPLETE, onFileLoaded);
file.load();
function onFileLoaded(e:Event):void
{
file.removeEventListener(Event.COMPLETE, onFileLoaded);
// now that we have the file bytes, we can upload the bytes.
var task:UploadTask = mountainImagesRef.putBytes(file.data);
task.addEventListener(StorageEvents.TASK_FAILED, onUploadBytesFailed);
task.addEventListener(StorageEvents.TASK_PROGRESS, onUploadBytesProgress);
task.addEventListener(StorageEvents.TASK_SUCCESS, onUploadBytesSuccess);
}
function onUploadBytesFailed(e:StorageEvents):void
{
trace("onUploadBytesFailed with errorCode '" + e.errorCode + "' and msg: " + e.msg);
}
function onUploadBytesProgress(e:StorageEvents):void
{
var task:UploadTask = e.currentTarget as UploadTask;
var percent:Number = task.bytesTransferred / task.bytesTotal * 100;
trace("onUploadBytesProgress = " + Math.floor(percent) + "%");
}
function onUploadBytesSuccess(e:StorageEvents):void
{
var task:UploadTask = e.currentTarget as UploadTask;
trace("bucket = " + task.metadata.bucket);
trace("cacheControl = " + task.metadata.cacheControl);
trace("contentDisposition = " + task.metadata.contentDisposition);
trace("contentEncoding = " + task.metadata.contentEncoding);
trace("contentLanguage = " + task.metadata.contentLanguage);
trace("contentType = " + task.metadata.contentType);
trace("creationTimeMillis = " + new Date(task.metadata.creationTimeMillis).toLocaleString());
trace("updatedTimeMillis = " + new Date(task.metadata.updatedTimeMillis).toLocaleString());
trace("customMetadata = " + JSON.stringify(task.metadata.customMetadata));
trace("generation = " + task.metadata.generation);
trace("metadataGeneration = " + task.metadata.metadataGeneration);
trace("name = " + task.metadata.name);
trace("path = " + task.metadata.path);
trace("sizeBytes = " + task.metadata.sizeBytes);
}
Because putBytes()
accepts a ByteArray
, it requires your app to hold the entire contents of a file in memory at once. Consider using putFile()
to use less memory.
You can upload local files on the device, such as photos and videos from the camera, with the putFile() method. putFile()
takes a File and returns an UploadTask which you can use to manage and monitor the status of the upload.
// to use the "putFile()" method, your file must be in File.documentsDirectory or File.applicationStorageDirectory
var file:File = File.applicationStorageDirectory.resolvePath("myBigFile.zip");
var bigFileRef:StorageReference = rootRef.child("files/myBigFile.zip");
var task:UploadTask = bigFileRef.putFile(file);
// Begin monitoring the upload progress with these listeners
task.addEventListener(StorageEvents.TASK_FAILED, onUploadFileFailed);
task.addEventListener(StorageEvents.TASK_PAUSED, onUploadFilePaused);
task.addEventListener(StorageEvents.TASK_PROGRESS, onUploadFileProgress);
task.addEventListener(StorageEvents.TASK_SUCCESS, onUploadFileSuccess);
You can also include metadata when you upload files. This metadata contains typical file metadata properties such as name, size, and contentType (commonly referred to as MIME type). The putFile()
method automatically infers the MIME type from the File extension, but you can override the auto-detected type by specifying contentType in the metadata. If you do not provide a contentType and Firebase Storage cannot infer a default from the file extension, Firebase Storage uses application/octet-stream. See the Use File Metadata section for more information about file metadata.
// Create file metadata including the content type
var metadata:StorageMetadata = new StorageMetadata(null, null, null, null, null, "image/jpg");
// Upload the file and metadata
var task:UploadTask = bigFileRef.putFile(file, metadata);
In addition to starting uploads, you can pause, resume, and cancel uploads using the pause()
, resume()
, and cancel()
methods. Pause and resume events raise pause and progress state changes respectively. Canceling an upload causes the upload to fail with an error indicating that the upload was canceled.
var task:UploadTask = bigFileRef.putFile(file);
// Pause the upload
task.pause();
// Resume the upload
task.resume();
// Cancel the upload
task.cancel();
You can add listeners to handle success, failure, progress, or pauses in your upload task. These listeners provide a simple and powerful way to monitor upload events.
// Begin monitoring the upload progress with these listeners
uploadTask.addEventListener(StorageEvents.TASK_FAILED, onUploadFileFailed);
uploadTask.addEventListener(StorageEvents.TASK_PAUSED, onUploadFilePaused);
uploadTask.addEventListener(StorageEvents.TASK_PROGRESS, onUploadFileProgress);
uploadTask.addEventListener(StorageEvents.TASK_SUCCESS, onUploadFileSuccess);
function onUploadFileFailed(e:StorageEvents):void
{
trace(e.errorCode) // error codes are explained in the StorageExceptions class
trace(e.msg)
}
function onUploadFilePaused(e:StorageEvents):void
{
// this event is called when you pause the task using uploadTask.pause();
}
function onUploadFileProgress(e:StorageEvents):void
{
// when the task is running, you can find out the transfered bytes
var percent:Number = uploadTask.bytesTransferred / uploadTask.bytesTotal * 100;
}
function onUploadFileSuccess(e:StorageEvents):void
{
trace("bucket = " + uploadTask.metadata.bucket);
trace("cacheControl = " + uploadTask.metadata.cacheControl);
trace("contentDisposition = " + uploadTask.metadata.contentDisposition);
trace("contentEncoding = " + uploadTask.metadata.contentEncoding);
trace("contentLanguage = " + uploadTask.metadata.contentLanguage);
trace("contentType = " + uploadTask.metadata.contentType);
trace("creationTimeMillis = " + new Date(uploadTask.metadata.creationTimeMillis).toLocaleString());
trace("updatedTimeMillis = " + new Date(uploadTask.metadata.updatedTimeMillis).toLocaleString());
trace("customMetadata = " + JSON.stringify(uploadTask.metadata.customMetadata));
trace("generation = " + uploadTask.metadata.generation);
trace("metadataGeneration = " + uploadTask.metadata.metadataGeneration);
trace("name = " + uploadTask.metadata.name);
trace("path = " + uploadTask.metadata.path);
trace("sizeBytes = " + uploadTask.metadata.sizeBytes);
}
IMPORTANT make sure you are removing the listeners in the StorageEvents.TASK_SUCCESS
or StorageEvents.TASK_FAILED
events. These listeners are overridden in AS3 and are calling native commands. forgetting to remove them may cause unexpected behavior.
NOTE: This feature works on Android only at the moment. As soon as Firebase added the iOS support, we will also upgrade the ANE to have it available for the iOS too.
If your process is shut down, any uploads in progress will be interrupted. However, you can continue uploading once the process restarts by resuming the upload session with the server. This can save time and bandwidth by not starting the upload from the start of the file.
To do this, begin uploading via putFile
. On the resulting UploadTask
, call uploadSessionUri and save the resulting value in persistent storage (such as flash.data.EncryptedLocalStore
).
After your process restarts with an interrupted upload, call putFile
again. But this time also pass the uploadSessionUri
that was saved.
// the metadata must be the same as the first metadata you called when beginning the upload.
fileUploadTask = ref.putFile(file, metadata, getEncryptedLocalStore("uploadSessionUri"));
function getEncryptedLocalStore($key:String):String
{
var value:ByteArray = EncryptedLocalStore.getItem($key);
if (!value) return null;
return value.readUTFBytes(value.length);
}
Enjoy building Air apps – With ♥ from MyFlashLabs Team
Introduction to Firebase ANEs collection for Adobe Air apps
Get Started with Firebase Core in AIR
- Prerequisites
- Add Firebase to your app
- Add the Firebase SDK
- Init Firebase Core
- Available ANEs
- Managing Firebase iid
Get Started with Authentication
- Add Authentication
- Init Authentication
- Manage Users
- Phone Number
- Custom Auth
- Anonymous Auth
- State in Email Actions
- Email Link Authentication
Get Started with FCM + OneSignal
- Add FCM ANE
- Init FCM ANE
- Send Your 1st Message
- Send Msg to Topics
- Understanding FCM Messages
- init OneSignal
- Add Firestore
- Init Firestore
- Add Data
- Transactions & Batches
- Delete Data
- Manage the Console
- Get Data
- Get Realtime Updates
- Simple and Compound
- Order and Limit Data
- Paginate Data
- Manage Indexes
- Secure Data
- Offline Data
- Where to Go From Here
Get Started with Realtime Database
- Add Realtime Database
- Init Realtime Database
- Structure Your Database
- Save Data
- Retrieve Data
- Enable Offline Capabilities
Get Started with Remote Config
- Add Storage ANE
- Init Storage ANE
- Upload Files to Storage
- Download Files to Air
- Use File Metadata
- Delete Files