[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后端开发而言真是非常的友善.因此这篇文章主要是对这段时间 ...
随机推荐
- [转载]CentOS 7虚拟机下设置固定IP详解
在 复制 他人作品之前,是因为我再此“跌倒”过一次,虽然原主说是永久地址,但是地址失效 不可避免.所以就原封不动的copy了过来,我自己也是按照他的一步一步配置的,我成功了,相信你们也会成功. 如果不 ...
- 第一章、zabbix安装
前言: 注意:本文不涉及性能测试.性能优化中的监控,所有文字的出发点都是日常运维监控. 在开始之前,我们还是先统一下认识:要监控一个对象,需要掌握哪些东西呢? 监控对象的理解:要监控的对象你是否了解呢 ...
- cookie 实现记住用户名演示 通过代码迅速理解cookie
// 登录页 可直接 tomcat部署 测试 1 package com.itheima.login; import java.io.IOException; import java.io.Print ...
- AP设备漫游阈值设置
在多个AP部署的场景下,默认情况下,手持移动设备(如PDA.手机)信号弱到断掉时才切换AP,无线信号很弱的情况下网络是非常的不稳定的,因此我们需要配置AP设备的漫游阈值(RSSI阈值),以便连接的无线 ...
- ArcGIS api for javascript——使用图层定义显示地图
描述 本例展示如何使用图层定义来限制显示在地图上的图层信息.为了了解本例做了什么,看看用于这个地图的ESRI_Census_USA服务的服务目录页是有帮助的.检查地图中的图层列表.现在注意这行代码限制 ...
- POJ 1035-Spell checker(字符串)
题目地址:POJ 1035 题意:输入一部字典.输入若干单词. 若某个单词能在字典中找到,则输出corret.若某个单词能通过 变换 或 删除 或 加入一个字符后.在字典中找得到.则输出这些单词.输出 ...
- Windows远程登录Linux
本文以Ubuntu Kylin1404为例,说明如何通过Windows远程登录Linux. 首先,要确保Ubuntu上SSH服务执行正常.默认情况下,Ubuntu已装有SSHclient.比方输入ss ...
- PHP Apache shutdown unexpectedly启动错误解释及解决的方法
在学PHP的时候,偶然发现XAMPP窗体Apache的启动出现错误,出现下面的错误提示: 9:52:41 [Apache] Attempting to start Apache app... 9:5 ...
- Simditor用法
一不小心接触到Simditor,瞬间被它优美极简的界面所吸引.Simditor是Tower开源的所见即所得的在线富文本编辑器. Simditor的理念是保持简单,避免过度的功能,每个特性都追求极致的用 ...
- jfinal文件上传与下载
import com.alibaba.fastjson.JSONObject; import com.jfinal.core.Controller; import com.jfinal.ext.kit ...