UNPKG

7.44 kBMarkdownView Raw
1# AngularFireStorage
2
3> Cloud Storage is designed to help you quickly and easily store and serve user-generated content, such as photos and videos.
4
5### Import the `NgModule`
6
7Cloud Storage for AngularFire is contained in the `@angular/fire/storage` module namespace. Import the `AngularFireStorageModule` in your `NgModule`. This sets up the `AngularFireStorage` service for dependency injection.
8
9```ts
10import { BrowserModule } from '@angular/platform-browser';
11import { NgModule } from '@angular/core';
12import { AppComponent } from './app.component';
13import { AngularFireModule } from '@angular/fire/compat';
14import { AngularFireStorageModule } from '@angular/fire/compat/storage';
15import { environment } from '../environments/environment';
16
17@NgModule({
18 imports: [
19 BrowserModule,
20 AngularFireModule.initializeApp(environment.firebase),
21 AngularFireStorageModule
22 ],
23 declarations: [ AppComponent ],
24 bootstrap: [ AppComponent ]
25})
26export class AppModule {}
27```
28
29The `BUCKET` injection token can be used to customise the storage bucket.
30
31```ts
32import {AngularFireStorageModule, BUCKET } from '@angular/fire/compat/storage';
33
34@NgModule({
35 providers: [
36 { provide: BUCKET, useValue: 'my-bucket-name' }
37 ],
38 ...
39})
40export class AppModule {}
41```
42
43### Injecting the AngularFireStorage service
44
45Once the `AngularFireStorageModule` is registered you can inject the `AngularFireStorage` service.
46
47```ts
48import { Component } from '@angular/core';
49import { AngularFireStorage } from '@angular/fire/compat/storage';
50
51@Component({
52 selector: 'app-component',
53 template: ``
54})
55export class AppComponent {
56 constructor(private storage: AngularFireStorage) { }
57}
58```
59
60### Uploading blobs
61
62There are three options for uploading files.
63
64
65| method | |
66| ---------|--------------------|
67| `put(data: Blob, metadata?: storage.UploadMetadata): AngularFireUploadTask` | Starts the upload of the blob to the storage reference's path. Returns an `AngularFireUploadTask` for upload monitoring. |
68| `putString(data: string, format?: StringFormat, metadata?: UploadMetadata): AngularFireUploadTask` | Updates an existing item in the array. Accepts a key, database reference, or an unwrapped snapshot. |
69| `upload(path: string, data: StringFormat, metadata?: UploadMetadata): AngularFireUploadTask` | Upload or update a new file to the storage reference's path. Returns an `AngularFireUploadTask` for upload monitoring. |
70
71### Examples
72
73#### Uploading blobs with put
74
75```ts
76import { Component } from '@angular/core';
77import { AngularFireStorage } from '@angular/fire/compat/storage';
78
79@Component({
80 selector: 'app-root',
81 template: `
82 <input type="file" (change)="uploadFile($event)">
83 `
84})
85export class AppComponent {
86 constructor(private storage: AngularFireStorage) { }
87 uploadFile(event) {
88 const file = event.target.files[0];
89 const filePath = 'name-your-file-path-here';
90 const ref = this.storage.ref(filePath);
91 const task = ref.put(file);
92 }
93}
94```
95
96#### Uploading blobs with putString
97
98```ts
99import { Component } from '@angular/core';
100import { AngularFireStorage } from '@angular/fire/compat/storage';
101
102@Component({
103 selector: 'app-root',
104 template: `
105 <input type="file" (change)="uploadFile($event)">
106 `
107})
108export class AppComponent {
109 constructor(private storage: AngularFireStorage) { }
110 uploadFile(event) {
111 const file = event.target.files[0];
112 const filePath = 'name-your-file-path-here';
113 const ref = this.storage.ref(filePath);
114 const task = ref.putString(file);
115 }
116}
117```
118
119#### Uploading files with upload
120
121```ts
122import { Component } from '@angular/core';
123import { AngularFireStorage } from '@angular/fire/compat/storage';
124
125@Component({
126 selector: 'app-root',
127 template: `
128 <input type="file" (change)="uploadFile($event)">
129 `
130})
131export class AppComponent {
132 constructor(private storage: AngularFireStorage) { }
133 uploadFile(event) {
134 const file = event.target.files[0];
135 const filePath = 'name-your-file-path-here';
136 const task = this.storage.upload(filePath, file);
137 }
138}
139```
140
141### Monitoring upload percentage
142
143An `AngularFireUploadTask` has methods for observing upload percentage as well as the final download URL.
144
145| method | |
146| ---------|--------------------|
147| `snapshotChanges(): Observable<FirebaseStorage.UploadTaskSnapshot>` | Emits the raw `UploadTaskSnapshot` as the file upload progresses. |
148| `percentageChanges(): Observable<number>` | Emits the upload completion percentage. |
149| `getDownloadURL(): Observable<any>` | Emits the download url when available |
150
151#### Example Usage
152
153The method `getDownloadURL()` doesn't rely on the task anymore, hence, in order to get the url we should use the finalize method from RxJS on top of the storage ref.
154
155```ts
156import { finalize } from 'rxjs/operators';
157
158@Component({
159 selector: 'app-root',
160 template: `
161 <input type="file" (change)="uploadFile($event)" />
162 <div>{{ uploadPercent | async }}</div>
163 <a [href]="downloadURL | async">{{ downloadURL | async }}</a>
164 `
165})
166export class AppComponent {
167 uploadPercent: Observable<number>;
168 downloadURL: Observable<string>;
169 constructor(private storage: AngularFireStorage) {}
170 uploadFile(event) {
171 const file = event.target.files[0];
172 const filePath = 'name-your-file-path-here';
173 const fileRef = this.storage.ref(filePath);
174 const task = this.storage.upload(filePath, file);
175
176 // observe percentage changes
177 this.uploadPercent = task.percentageChanges();
178 // get notified when the download URL is available
179 task.snapshotChanges().pipe(
180 finalize(() => this.downloadURL = fileRef.getDownloadURL() )
181 )
182 .subscribe()
183 }
184}
185```
186
187### Downloading Files
188
189A convenient pipe exists for simple in page references.
190
191```ts
192@Component({
193 selector: 'app-root',
194 template: `<img [src]="'users/davideast.jpg' | getDownloadURL" />`
195})
196export class AppComponent {}
197```
198
199To download a file you'll need to create a reference and call the `getDownloadURL()` method on an `AngularFireStorageReference`.
200
201```ts
202@Component({
203 selector: 'app-root',
204 template: `<img [src]="profileUrl | async" />`
205})
206export class AppComponent {
207 profileUrl: Observable<string | null>;
208 constructor(private storage: AngularFireStorage) {
209 const ref = this.storage.ref('users/davideast.jpg');
210 this.profileUrl = ref.getDownloadURL();
211 }
212}
213```
214
215### Managing Metadata
216
217Cloud Storage for Firebase allows you to upload and download metadata associated with files. This is useful because you can store important metadata and download it without needing to download the entire file.
218
219### Examples
220
221#### Downloading metadata
222
223```ts
224@Component({
225 selector: 'app-root',
226 template: `<pre><code>{{ meta | async }}</code></pre>`
227})
228export class AppComponent {
229 meta: Observable<any>;
230 constructor(private storage: AngularFireStorage) {
231 const ref = this.storage.ref('users/davideast.jpg');
232 this.meta = ref.getMetadata();
233 }
234}
235```
236
237#### Uploading metadata with files
238
239```ts
240@Component({
241 selector: 'app-root',
242 template: `
243 <input type="file" (change)="uploadFile($event)" />
244 `
245})
246export class AppComponent {
247 constructor(private storage: AngularFireStorage) {}
248 uploadFile(event) {
249 const file = event.target.files[0];
250 const filePath = 'name-your-file-path-here';
251 const ref = this.storage.ref(filePath);
252 const task = ref.put(file, { customMetadata: { blah: 'blah' } });
253 }
254}
255```