Skip to content
This repository was archived by the owner on Mar 17, 2025. It is now read-only.

Commit fe25154

Browse files
authored
feat(docs): Firebase Storage docs (#902)
* feat(docs): Initial draft of Firebase Storage docs * feat(docs): () API Reference * feat(docs): UploadTask API Reference * fix(docs): Fix # links in the docs * chore(docs): Jacob's comments * chore(docs): Jacob's comments * chore(docs): Jacob's comments * chore(docs): Jacob's comments * chore(docs): Jacob's comments * chore(docs): Make it on one line
1 parent 94ca5bc commit fe25154

File tree

4 files changed

+365
-5
lines changed

4 files changed

+365
-5
lines changed

docs/guide/README.md

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
1. [Introduction to AngularFire](introduction-to-angularfire.md) - Learn about what AngularFire is and how to integrate it into your Angular app.
44
2. [Synchronized Objects](synchronized-objects.md) - Create synchronized objects and experience three-way data binding.
55
3. [Synchronized Arrays](synchronized-arrays.md) - Create and modify arrays which stay in sync with the database.
6-
4. [User Authentication](user-auth.md) - AngularFire handles user authentication and session management for you.
7-
5. [Extending the Services](extending-services.md) - Advanced users can extend the functionality of the built-in AngularFire services.
8-
6. [Beyond AngularFire](beyond-angularfire.md) - AngularFire is not the only way to use Angular and Firebase together.
6+
4. [Uploading & Downloading Binary Content](uploading-downloading-binary-content.md) - Store and retrieve content like images, audio, and video.
7+
5. [User Authentication](user-auth.md) - AngularFire handles user authentication and session management for you.
8+
6. [Extending the Services](extending-services.md) - Advanced users can extend the functionality of the built-in AngularFire services.
9+
7. [Beyond AngularFire](beyond-angularfire.md) - AngularFire is not the only way to use Angular and Firebase together.

docs/guide/synchronized-arrays.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -211,5 +211,5 @@ app.controller("ChatCtrl", ["$scope", "chatMessages",
211211

212212
Head on over to the [API reference](/docs/reference.md#firebasearray)
213213
for `$firebaseArray` to see more details for each API method provided by the service. Now that we
214-
have a grasp of synchronizing data with AngularFire, the [next section](user-auth.md) of this guide
215-
moves on to a different aspect of building applications: user authentication.
214+
have a grasp of synchronizing data with AngularFire, the [next section](uploading-downloading-binary-content.md) of this guide
215+
moves on to a different aspect of building applications: binary storage.
Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
# Uploading & Downloading Binary Content | AngularFire Guide
2+
3+
## Table of Contents
4+
5+
* [Overview](#overview)
6+
* [API Summary](#api-summary)
7+
* [Uploading Files](#uploading-files)
8+
* [Displaying Images with the `firebase-src` Directive](#displaying-images-with-the-firebase-src-directive)
9+
* [Retrieving Files from the Template](#retrieving-files-from-the-template)
10+
11+
## Overview
12+
13+
Firebase provides [a hosted binary storage service](https://firebase.google.com/docs/storage/)
14+
which enables you to store and retrieve user-generated content like images, audio, and
15+
video directly from the Firebase client SDK.
16+
17+
Binary files are stored in a Firebase Storage bucket, not in the Realtime Database.
18+
The files in your bucket are stored in a hierarchical structure, just like
19+
in the Realtime Database.
20+
21+
To use the Firebase Storage binding, first [create a Firebase Storage reference](https://firebase.google.com/docs/storage/web/create-reference).
22+
Then, using this reference, pass it into the `$firebaseStorage` service:
23+
24+
```js
25+
// define our app and dependencies (remember to include firebase!)
26+
angular
27+
.module("sampleApp", [
28+
"firebase"
29+
])
30+
.controller("SampleCtrl", SampleCtrl);
31+
32+
// inject $firebaseStorage into our controller
33+
function SampleCtrl($firebaseStorage) {
34+
// create a Firebase Storage Reference for the $firebaseStorage binding
35+
var storageRef = firebase.storage().ref("userProfiles/physicsmarie");
36+
var storage = $firebaseStorage(storageRef);
37+
}
38+
SampleCtrl.$inject = ["$firebaseStorage"];
39+
```
40+
41+
## API Summary
42+
43+
The Firebase Storage service is created with several special `$` methods, all of which are listed in the following table:
44+
45+
| Method | Description |
46+
| ------------- | ------------- |
47+
| [`$put(file, metadata)`](/docs/reference.md#putfile-metadata) | Uploads file to configured path with optional metadata. Returns an AngularFire wrapped [`UploadTask`](/docs/reference.md#upload-task). |
48+
| [`$putString(string, format, metadata)`](/docs/reference.md#putstringstring-format-metadata) | Uploads a upload a raw, base64, or base64url encoded string with optional metadata. Returns an AngularFire wrapped [`UploadTask`](/docs/reference.md#upload-task). |
49+
| [`$getDownloadURL()`](/docs/reference.md#getdownloadurl) | Returns a `Promise` fulfilled with the download URL for the file stored at the configured path. |
50+
| [`$getMetadata()`](/docs/reference.md#getmetadata) | Returns a `Promise` fulfilled with the metadata of the file stored at the configured path. |
51+
| [`$updateMetadata(metadata)`](/docs/reference.md#updatemetadatametadata) | Returns a `Promise` containing the updated metadata. |
52+
| [`$delete()`](/docs/reference.md#delete) | Permanently deletes the file stored at the configured path. Returns a `Promise` that is resolved when the delete completes. |
53+
| [`$toString()`](/docs/reference.md#tostring) | Returns a string version of the bucket path stored as a `gs://` scheme. |
54+
55+
56+
## Uploading files
57+
To upload files, use either the `$put()` or `$putString()` methods. These methods
58+
return an [[`UploadTask`](/docs/reference.md#upload-task)(https://firebase.google.com/docs/reference/js/firebase.storage#uploadtask) which is wrapped by AngularFire to handle the `$digest` loop.
59+
60+
```js
61+
function SampleCtrl($firebaseStorage) {
62+
// create a Firebase Storage Reference for the $firebaseStorage binding
63+
var storageRef = firebase.storage().ref('userProfiles/physicsmarie');
64+
var storage = $firebaseStorage(storageRef);
65+
var file = // get a file from the template (see Retrieving files from template section below)
66+
var uploadTask = storage.$put(file);
67+
// of upload via a RAW, base64, or base64url string
68+
var stringUploadTask = storage.$putString('5b6p5Y+344GX44G+44GX44Gf77yB44GK44KB44Gn44Go44GG77yB', 'base64');
69+
}
70+
SampleCtrl.$inject = ["$firebaseStorage"];
71+
```
72+
73+
### Upload Task API Summary
74+
75+
| Method | Description |
76+
| ------------- | ------------- |
77+
| [`$progress(callback)`](/docs/reference.md#progresscallback) | Calls the provided callback function whenever there is an update in the progress of the file uploading. |
78+
| [`$error(callback)`](/docs/reference.md#errorcallback) | Calls the provided callback function when there is an error uploading the file. |
79+
| [`$complete(callback)`](/docs/reference.md#completecallback) | Calls the provided callback function when the upload is complete. |
80+
| [`$cancel()`](/docs/reference.md#cancel) | Cancels the upload. |
81+
| [`$pause()`](/docs/reference.md#pause) | Pauses the upload. |
82+
| [`$snapshot()`](/docs/reference.md#snapshot) | Returns the [current immutable view of the task](https://firebase.google.com/docs/storage/web/upload-files#monitor_upload_progress) at the time the event occurred. |
83+
| [`then(callback)`](/docs/reference.md#then) | An [`UploadTask`](/docs/reference.md#upload-task) implements a `Promise` like interface. This callback is called when the upload is complete. |
84+
| [`catch(callback)`](/docs/reference.md#catch) | An [`UploadTask`](/docs/reference.md#upload-task) implements a `Promise` like interface. This callback is called when an error occurs. |
85+
86+
## Displaying Images with the `firebase-src` Directive
87+
88+
AngularFire provides a directive that displays a file with any `src`-compatible element. Instead of using the tradional `src` attribute, use `firebase-src`:
89+
90+
```html
91+
<img firebase-src="userProfiles/physicsmarie" />
92+
<!-- Works with bindings as well -->
93+
<img firebase-src="{{ userProfileId }}" />
94+
```
95+
96+
## Retrieving Files from the Template
97+
98+
AngularFire does not provide a directive for retrieving an uploaded file. However,
99+
the directive below provides a baseline to work off:
100+
101+
```js
102+
angular
103+
.module("sampleApp", [
104+
"firebase"
105+
])
106+
.directive("fileUpload", FileUploadDirective);
107+
108+
function FileUploadDirective() {
109+
return {
110+
restrict: "E",
111+
transclude: true,
112+
scope: {
113+
onChange: "="
114+
},
115+
template: '<input type="file" name="file" /><label><ng-transclude></ng-transclude></label>',
116+
link: function (scope, element, attrs) {
117+
element.bind("change", function () {
118+
scope.onChange(element.children()[0].files);
119+
});
120+
}
121+
}
122+
}
123+
```
124+
125+
To use this directive, create a controller to bind the `onChange()` method:
126+
127+
```js
128+
function UploadCtrl($firebaseStorage) {
129+
var ctrl = this;
130+
var storageRef = firebase.storage().ref("userProfiles/physicsmarie");
131+
var storage = $firebaseStorage(storageRef);
132+
ctrl.fileToUpload = null;
133+
ctrl.onChange = function onChange(fileList) {
134+
ctrl.fileToUpload = fileList[0];
135+
};
136+
}
137+
```
138+
139+
Then specify your template to use the directive:
140+
141+
```html
142+
<div ng-controller="UploadCtrl as $ctrl">
143+
<file-upload on-change="$ctrl.onChange">
144+
Upload
145+
</file-upload>
146+
</div>
147+
```
148+
149+
Head on over to the [API reference](/docs/reference.md#firebasestorage)
150+
for `$firebaseStorage` to see more details for each API method provided by the service. Now that we
151+
have a grasp of managing binary content with AngularFire, the [next section](user-auth.md) of this guide
152+
moves on to a new topic: authentication.

docs/reference.md

Lines changed: 207 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,23 @@
4444
* Router Helpers
4545
* [`$waitForSignIn()`](#waitforsignin)
4646
* [`$requireSignIn(requireEmailVerification)`](#requiresigninrequireemailverification)
47+
* [`$firebaseStorage`](#firebasestorage)
48+
* [`$put(file, metadata)`](#putfile-metadata)
49+
* [`$putString(string, format, metadata)`](#putstringstring-format-metadata)
50+
* [`$getDownloadURL()`](#getdownloadurl)
51+
* [`$getMetadata()`](#getmetadata)
52+
* [`$updateMetadata(metadata)`](#updatemetadatametadata)
53+
* [`$delete()`](#delete)
54+
* [`$toString()`](#tostring)
55+
* [Upload Task](#upload-task)
56+
* [`$progress(callback)`](#progresscallback)
57+
* [`$complete(callback)`](#completecallback)
58+
* [`$error(callback)`](#errorcallback)
59+
* [`$cancel()`](#cancel)
60+
* [`$pause()`](#pause)
61+
* [`$snapshot()`](#snapshot)
62+
* [`then(callback)`](#then)
63+
* [`catch(callback)`](#catch)
4764
* [Extending the Services](#extending-the-services)
4865
* [Extending `$firebaseObject`](#extending-firebaseobject)
4966
* [Extending `$firebaseArray`](#extending-firebasearray)
@@ -966,6 +983,196 @@ users from seeing authenticated pages momentarily during page load. See the
966983
["Using Authentication with Routers"](/docs/guide/user-auth.md#authenticating-with-routers)
967984
section of our AngularFire guide for more information and a full example.
968985

986+
## $firebaseStorage
987+
988+
AngularFire includes support for [binary storage](/docs/guide/uploading-downloading-binary-content.md)
989+
with the `$firebaseStorage` service.
990+
991+
The `$firebaseStorage` service takes a [Firebase Storage](https://firebase.google.com/docs/storage/) reference.
992+
993+
```js
994+
app.controller("MyCtrl", ["$scope", "$firebaseStorage",
995+
function($scope, $firebaseStorage) {
996+
var storageRef = firebase.storage().ref("images/dog");
997+
$scope.storage = $firebaseStorage(storageRef);
998+
}
999+
]);
1000+
```
1001+
1002+
The storage object returned by `$firebaseStorage` contains several methods for uploading and
1003+
downloading binary content, as well as managing the content's metadata.
1004+
1005+
### $put(file, metadata)
1006+
1007+
[Uploads a `Blob` object](https://firebase.google.com/docs/storage/web/upload-files) to the specified storage reference's path with an optional metadata parameter.
1008+
Returns an [`UploadTask`](#upload-task) wrapped by AngularFire.
1009+
1010+
1011+
```js
1012+
var htmlFile = new Blob(["<html></html>"], { type : "text/html" });
1013+
var uploadTask = $scope.storage.$put(htmlFile, { contentType: "text/html" });
1014+
```
1015+
1016+
### $putString(string, format, metadata)
1017+
1018+
[Uploads a raw, `base64` string, or `base64url` string](https://firebase.google.com/docs/storage/web/upload-files#upload_from_a_string) to the specified storage reference's path with an optional metadata parameter.
1019+
Returns an [`UploadTask`](#upload-task) wrapped by AngularFire.
1020+
1021+
```js
1022+
var base64String = "5b6p5Y+344GX44G+44GX44Gf77yB44GK44KB44Gn44Go44GG77yB";
1023+
// Note: valid values for format are "raw", "base64", "base64url", and "data_url".
1024+
var uploadTask = $scope.storage.$putString(base64String, "base64", { contentType: "image/gif" });
1025+
```
1026+
1027+
### $getDownloadURL()
1028+
1029+
Returns a promise fulfilled with [the download URL](https://firebase.google.com/docs/storage/web/download-files#download_data_via_url) for the file stored at the configured path.
1030+
1031+
```js
1032+
$scope.storage.$getDownloadURL().then(function(url) {
1033+
$scope.url = url;
1034+
});
1035+
```
1036+
1037+
### $getMetadata()
1038+
1039+
Returns a promise fulfilled with [the metadata of the file](https://firebase.google.com/docs/storage/web/file-metadata#get_file_metadata) stored at the configured path. File
1040+
metadata contains common properties such as `name`, `size`, and `contentType`
1041+
(often referred to as MIME type) in addition to some less common ones like `contentDisposition` and `timeCreated`.
1042+
1043+
```js
1044+
$scope.storage.$getMetadata().then(function(metadata) {
1045+
$scope.metadata = metadata;
1046+
});
1047+
```
1048+
1049+
### $updateMetadata(metadata)
1050+
1051+
[Updates the metadata of the file](https://firebase.google.com/docs/storage/web/file-metadata#update_file_metadata) stored at the configured path.
1052+
Returns a promise fulfilled with the updated metadata.
1053+
1054+
```js
1055+
var updateData = { contenType: "text/plain" };
1056+
$scope.storage.$updateMetadata(updateData).then(function(updatedMetadata) {
1057+
$scope.updatedMetadata = updatedMetadata;
1058+
});
1059+
```
1060+
1061+
### $delete()
1062+
1063+
Permanently [deletes the file stored](https://firebase.google.com/docs/storage/web/delete-files) at the configured path. Returns a promise that is resolved when the delete completes.
1064+
1065+
```js
1066+
$scope.storage.$delete().then(function() {
1067+
console.log("successfully deleted!");
1068+
});
1069+
```
1070+
1071+
### $toString()
1072+
1073+
Returns a [string version of the bucket path](https://firebase.google.com/docs/reference/js/firebase.storage.Reference#toString) stored as a `gs://` scheme.
1074+
1075+
```js
1076+
// gs://<bucket>/<path>/<to>/<object>
1077+
var asString = $scope.storage.$toString();
1078+
```
1079+
1080+
### Upload Task
1081+
1082+
The [`$firebaseStorage()`](#firebasestorage) service returns an AngularFire wrapped [`UploadTask`](https://firebase.google.com/docs/reference/js/firebase.storage#uploadtask) when uploading binary content
1083+
using the [`$put()`](#putfile-metadata) and [`$putString()`](#putstringstring-format-metadata) methods. This task is used for [monitoring](https://firebase.google.com/docs/storage/web/upload-files#monitor_upload_progress)
1084+
and [managing](https://firebase.google.com/docs/storage/web/upload-files#manage_uploads) uploads.
1085+
1086+
```js
1087+
var htmlFile = new Blob(["<html></html>"], { type : "text/html" });
1088+
var uploadTask = $scope.storage.$put(htmlFile, { contentType: "text/html" });
1089+
```
1090+
1091+
#### $progress(callback)
1092+
1093+
Calls the provided callback function whenever there is an update in the progress of the file uploading. The callback
1094+
passes back an [`UploadTaskSnapshot`](https://firebase.google.com/docs/reference/js/firebase.storage.UploadTaskSnapshot).
1095+
1096+
```js
1097+
var uploadTask = $scope.storage.$put(file);
1098+
uploadTask.$progress(function(snapshot) {
1099+
var percentUploaded = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
1100+
console.log(percentUploaded);
1101+
});
1102+
```
1103+
1104+
#### $complete(callback)
1105+
1106+
Calls the provided callback function when the upload is complete. Passes back the completed [`UploadTaskSnapshot`](https://firebase.google.com/docs/reference/js/firebase.storage.UploadTaskSnapshot).
1107+
1108+
```js
1109+
var uploadTask = $scope.storage.$put(file);
1110+
uploadTask.$complete(function(snapshot) {
1111+
console.log(snapshot.downloadURL);
1112+
});
1113+
```
1114+
1115+
#### $error(callback)
1116+
1117+
Calls the provided callback function when there is an error uploading the file.
1118+
1119+
```js
1120+
var uploadTask = $scope.storage.$put(file);
1121+
uploadTask.$error(function(error) {
1122+
console.error(error);
1123+
});
1124+
```
1125+
1126+
#### $cancel()
1127+
1128+
[Cancels](https://firebase.google.com/docs/reference/js/firebase.storage.UploadTask#cancel) the current upload.
1129+
Has no effect on a completed upload. Returns `true` if cancel had effect.
1130+
1131+
```js
1132+
var uploadTask = $scope.storage.$put(file);
1133+
var hadEffect = uploadTask.$cancel();
1134+
```
1135+
1136+
#### $pause()
1137+
1138+
[Pauses](https://firebase.google.com/docs/reference/js/firebase.storage.UploadTask#pause) the current upload.
1139+
Has no effect on a completed upload. Returns `true` if pause had effect.
1140+
1141+
```js
1142+
var uploadTask = $scope.storage.$put(file);
1143+
var hadEffect = uploadTask.$pause();
1144+
```
1145+
1146+
#### $snapshot()
1147+
1148+
Returns the [current immutable view of the task](https://firebase.google.com/docs/reference/js/firebase.storage.UploadTaskSnapshot) at the time the event occurred.
1149+
1150+
```js
1151+
var uploadTask = $scope.storage.$put(file);
1152+
$scope.bytesTransferred = uploadTask.$snapshot.bytesTransferred;
1153+
```
1154+
1155+
#### then()
1156+
An `UploadTask` implements a promise like interface. The callback is called when the upload is complete. The callback
1157+
passes back an [UploadTaskSnapshot](https://firebase.google.com/docs/reference/js/firebase.storage.UploadTaskSnapshot).
1158+
1159+
```js
1160+
var uploadTask = $scope.storage.$put(file);
1161+
uploadTask.then(function(snapshot) {
1162+
console.log(snapshot.downloadURL);
1163+
});
1164+
```
1165+
1166+
#### catch()
1167+
An `UploadTask` implements a promise like interface. The callback is called when an error occurs.
1168+
1169+
```js
1170+
var uploadTask = $scope.storage.$put(file);
1171+
uploadTask.catch(function(error) {
1172+
console.error(error);
1173+
});
1174+
```
1175+
9691176
## Extending the Services
9701177

9711178
There are several powerful techniques for transforming the data downloaded and saved

0 commit comments

Comments
 (0)