[AngularFire] Angular File Uploads to Firebase Storage with Angular control value accessor
The upload class will be used in the service layer. Notice it has a constructor for file attribute, which has a type of File. This will allows us to initialize new uploads with a JavaScript File object. You will see why this is important in the next step.
export class Upload {
$key: string;
file:File;
name:string;
url:string;
progress:number;
createdAt: Date = new Date();
constructor(file:File) {
this.file = file;
}
}
Then build the upload service, which can inject to component:
import { Injectable } from '@angular/core';
import {Subject} from 'rxjs/Subject';
import {MatSnackBar} from '@angular/material';
import * as firebase from 'firebase';
import UploadTaskSnapshot = firebase.storage.UploadTaskSnapshot;
import {Upload} from './upload';
@Injectable()
export class UploadService {
uploading$ = new Subject<number>();
completed$ = new Subject<Upload>();
constructor(
private snackBar: MatSnackBar
) {
}
uploadFile(upload: Upload, folder: string) {
// Create a storage ref
const storageRef = firebase.storage().ref();
const uploadTask = storageRef.child(`${folder}/${upload.file.name}`).put(upload.file);
// Upload file
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
(snapshot: UploadTaskSnapshot) => {
upload.progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
this.uploading$.next(upload.progress);
},
(err) => {
this.snackBar.open(err.message, 'OK', {
duration: 3000,
});
},
() => {
upload.url = uploadTask.snapshot.downloadURL;
upload.name = upload.file.name;
this.completed$.next(upload);
this.uploading$.next(null);
});
}
deleteUpload(name: string, folder: string) {
const storageRef = firebase.storage().ref();
storageRef.child(`${folder}/${name}`).delete();
this.completed$.next();
}
}
Component:
import {ChangeDetectionStrategy, Component, forwardRef, Input} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
import {UploadService} from '../../services/upload.service';
import {Upload} from '../../services/upload';
import {Observable} from 'rxjs/Observable';
export const TYPE_CONTROL_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
multi: true,
useExisting: forwardRef(() => ImageUploaderComponent)
};
@Component({
selector: 'image-uploader',
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [TYPE_CONTROL_ACCESSOR],
templateUrl: './image-uploader.component.html',
styleUrls: ['./image-uploader.component.scss']
})
export class ImageUploaderComponent implements ControlValueAccessor {
@Input() img;
private onTouch: Function;
private onModelChange: Function;
private value: string;
file: Upload;
currentUpload: Upload;
progress$: Observable<number>;
constructor(private uploadService: UploadService) {
this.progress$ = this.uploadService.uploading$;
this.uploadService.completed$.subscribe((upload) => {
if (upload) {
this.setSelected(upload.url);
this.currentUpload = upload;
} else {
this.setSelected('');
this.currentUpload = null;
}
});
}
onChange($event) {
const file = $event.target.files[0];
this.file = new Upload(file);
this.uploadService.uploadFile(this.file, 'icons');
}
writeValue(value: any): void {
this.value = value;
}
registerOnChange(fn: Function): void {
this.onModelChange = fn;
}
registerOnTouched(fn: Function): void {
this.onTouch = fn;
}
setSelected(value: string): void {
this.value = value;
this.onModelChange(value);
this.onTouch();
}
clear() {
if (this.file) {
this.uploadService.deleteUpload(this.file.name, 'icons');
this.setSelected('');
}
}
}
Template:
<div *ngIf="progress$ | async as p">
<mat-progress-bar mode="determinate" [value]="p"></mat-progress-bar>
</div>
<mat-card-subtitle>
Select / upload icon
</mat-card-subtitle> <mat-card-content fxLayout="column">
<div fxLayout="row" fxLayoutAlign="space-around">
<div
*ngIf="currentUpload"
class="image-container"
fxFlex="30%">
<img [src]="currentUpload?.url || ''" [alt]="currentUpload?.name || ''">
</div>
</div>
[AngularFire] Angular File Uploads to Firebase Storage with Angular control value accessor的更多相关文章
- [Angular] Implement a custom form component by using control value accessor
We have a form component: <label> <h3>Type</h3> <workout-type formControlName=& ...
- [转]File uploads in ASP.NET Core
本文转自:https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads By Steve Smith ASP.NET MVC ...
- Asp.net mvc 3 file uploads using the fileapi
Asp.net mvc 3 file uploads using the fileapi I was recently given the task of adding upload progress ...
- The lesser known pitfalls of allowing file uploads on your website
These days a lot of websites allow users to upload files, but many don’t know about the unknown pitf ...
- 从Java角度理解Angular之入门篇:npm, yarn, Angular CLI
本系列从Java程序员的角度,带大家理解前端Angular框架. 本文重点介绍Angular的开发.编译工具:npm, yarn, Angular CLI,它们就像Java在中的Maven,同时顺便介 ...
- (转载)从Java角度理解Angular之入门篇:npm, yarn, Angular CLI
本系列从Java程序员的角度,带大家理解前端Angular框架. 本文是入门篇.笔者认为亲自动手写代码做实验,是最有效最扎实的学习途径,而搭建开发环境是学习一门新技术最需要先学会的技能,是入门的前提. ...
- Angular 个人深究(一)【Angular中的Typescript 装饰器】
Angular 个人深究[Angular中的Typescript 装饰器] 最近进入一个新的前端项目,为了能够更好地了解Angular框架,想到要研究底层代码. 注:本人前端小白一枚,文章旨在记录自己 ...
- angular.module()创建、获取、注册angular中的模块
// 传递参数不止一个,代表新建模块;空数组代表该模块不依赖其他模块 var createModule = angular.module("myModule", []); // 只 ...
- Angular入门,开发环境搭建,使用Angular CLI创建你的第一个Angular项目
前言: 最近一直在使用阿里的NG-ZORRO(Angular组件库)开发公司后端的管理系统,写了一段时间的Angular以后发现对于我们.NET后端开发而言真是非常的友善.因此这篇文章主要是对这段时间 ...
随机推荐
- caioj 1618 【动态规划】矩阵相乘的次数
刷刷水题压压惊 低级版的能量项链 相当于复习一次中链式dp 这种合并了之后又后效性的题目 都可以用类似的方法做 #include<cstdio> #include<cstring&g ...
- HDFS文件系统上传时序图 PB级文件存储时序图
自己设计的时序图. 来自为知笔记(Wiz)
- ArcGIS api for javascript——用缓存区查询地图
描述 本例展示了如何在另外一个任务里使用一个任务的结果.单击地图查看被单击的点的1公里范围内的缓存(如果需要可以修改这个默认的缓存距离).也可以看缓存区的这些点的人口普查街区信息.单击一个点查看更多的 ...
- Option可选值(一)
//: Playground - noun: a place where people can play import Cocoa class Person { var residence: Resi ...
- 查看SQLSERVER当前正在运行的sql信息
能够使用SQL Profiler捕捉在SQL Server实例上运行的活动.这种活动被称为Profiler跟踪.这个就不多说了,大家都知道,以下是使用代码为实现同样的效果. SET TRANSACTI ...
- 五大最受欢迎的BUG管理系统
Google在中国大陆遭遇变故做出临时性的退出大陆市场,也使非常多忠实的用户受到小小的挫折,以本公司为例.原本的BUG都是记录在google的 EXCEL在线文档中,由于常常性的打不开.測试和开发组在 ...
- Android LruCache 压缩图片 有效避免程序OOM
转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/9316683 本篇文章主要内容来自于Android Doc,我翻译之后又做了些加工, ...
- Redis封装之List
/// <summary> /// Redis list的实现为一个双向链表,即可以支持反向查找和遍历,更方便操作,不过带来了部分额外的内存开销, /// Redis内部的很多实现,包括发 ...
- spring security源码分析心得
看了半天的文档及源码,终于理出了spring-security的一些总体思路,spring security主要分认证(authentication)和授权(authority). 1.认证authe ...
- netflix turbine概述
1.turbine是什么?它的作用是什么? Turbine is a tool for aggregating streams of Server-Sent Event (SSE) JSON data ...