Skip to content
This repository has been archived by the owner on May 17, 2022. It is now read-only.

E.3 Upload Files

Hadi Tavakoli edited this page Sep 26, 2018 · 3 revisions

Upload files to Firebase Storage

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.

Upload from data in memory

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.

Upload from a local file

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);

Add File Metadata

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);

Manage Uploads

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();

Monitor Upload Progress

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.

Continuing Uploads Across Process Restarts

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);
}

Introduction to Firebase ANEs collection for Adobe Air apps


Get Started with Firebase Core in AIR

  1. Prerequisites
  2. Add Firebase to your app
  3. Add the Firebase SDK
  4. Init Firebase Core
  5. Available ANEs
  6. Managing Firebase iid

Get Started with Analytics

  1. Add Analytics ANE
  2. Init Analytics ANE
  3. Log Events
  4. Set User Properties

Get Started with Crashlytics

  1. Add Crashlytics ANE
  2. Test Your Implementation
  3. Customize Crash Reports
  4. Upload .dSYM for iOS apps

Get Started with DynamicLinks

  1. Add DynamicLinks ANE
  2. Init DynamicLinks ANE
  3. Create DynamicLinks
  4. Receive DynamicLinks
  5. View Analytics

Get Started with Authentication

  1. Add Authentication
  2. Init Authentication
  3. Manage Users
  4. Phone Number
  5. Custom Auth
  6. Anonymous Auth
  7. State in Email Actions
  8. Email Link Authentication

Get Started with FCM + OneSignal

  1. Add FCM ANE
  2. Init FCM ANE
  3. Send Your 1st Message
  4. Send Msg to Topics
  5. Understanding FCM Messages
  6. init OneSignal

Get Started with Firestore

  1. Add Firestore
  2. Init Firestore
  3. Add Data
  4. Transactions & Batches
  5. Delete Data
  6. Manage the Console
  7. Get Data
  8. Get Realtime Updates
  9. Simple and Compound
  10. Order and Limit Data
  11. Paginate Data
  12. Manage Indexes
  13. Secure Data
  14. Offline Data
  15. Where to Go From Here

Get Started with Realtime Database

  1. Add Realtime Database
  2. Init Realtime Database
  3. Structure Your Database
  4. Save Data
  5. Retrieve Data
  6. Enable Offline Capabilities

Get Started with Remote Config

  1. Parameters and Conditions
  2. Add Remote Config
  3. Init Remote Config

Get Started with Performance

  1. Add Performance ANE
  2. Init & Start Monitoring

Get Started with Storage

  1. Add Storage ANE
  2. Init Storage ANE
  3. Upload Files to Storage
  4. Download Files to Air
  5. Use File Metadata
  6. Delete Files

Get Started with Functions

  1. Write & Deploy Functions
  2. Add Functions ANE
  3. Init Functions
Clone this wiki locally