1 onFileChange(event) {
2 let reader = new FileReader();
3 if(event.target.files && event.target.files.length > 0) {
4 let file = event.target.files[0];
5 reader.readAsDataURL(file);
6 reader.onload = () => {
7 this.form.get('avatar').setValue({
8 filename: file.name,
9 filetype: file.type,
10 value: reader.result.split(',')[1]
11 })
12 };
13 }
14 }
15
1// src/app/base64-upload/base64-upload.component.html
2
3<form [formGroup]="form" (ngSubmit)="onSubmit()">
4 <div class="form-group">
5 <label for="name">Name</label>
6 <input type="text" class="form-control" id="name" placeholder="Bob" formControlName="name">
7 </div>
8 <div class="form-group">
9 <label for="avatar">Avatar</label>
10 <input type="file" id="avatar" (change)="onFileChange($event)" #fileInput>
11 <button type="button" class="btn btn-sm btn-default" (click)="clearFile()">clear file</button>
12 </div>
13 <button type="submit" [disabled]="form.invalid || loading" class="btn btn-success">Submit <i class="fa fa-spinner fa-spin fa-fw" *ngIf="loading"></i></button>
14</form>
15
1// src/app/formdata-upload/base64-upload.component.ts
2
3import {Component, ElementRef, ViewChild} from '@angular/core';
4import {FormBuilder, FormGroup, Validators} from "@angular/forms";
5
6@Component({
7 selector: 'base64-upload',
8 templateUrl: './base64-upload.component.html'
9})
10export class Base64UploadComponent {
11 form: FormGroup;
12 loading: boolean = false;
13
14 @ViewChild('fileInput') fileInput: ElementRef;
15
16 constructor(private fb: FormBuilder) {
17 this.createForm();
18 }
19
20 createForm() {
21 this.form = this.fb.group({
22 name: ['', Validators.required],
23 avatar: null
24 });
25 }
26
27 onFileChange(event) {
28 let reader = new FileReader();
29 if(event.target.files && event.target.files.length > 0) {
30 let file = event.target.files[0];
31 reader.readAsDataURL(file);
32 reader.onload = () => {
33 this.form.get('avatar').setValue({
34 filename: file.name,
35 filetype: file.type,
36 value: reader.result.split(',')[1]
37 })
38 };
39 }
40 }
41
42 onSubmit() {
43 const formModel = this.form.value;
44 this.loading = true;
45 // In a real-world app you'd have a http request / service call here like
46 // this.http.post('apiUrl', formModel)
47 setTimeout(() => {
48 console.log(formModel);
49 alert('done!');
50 this.loading = false;
51 }, 1000);
52 }
53
54 clearFile() {
55 this.form.get('avatar').setValue(null);
56 this.fileInput.nativeElement.value = '';
57 }
58}
59