Last active
September 27, 2017 16:30
-
-
Save mmccall10/3c99a75261a764f2054d9d9ba2d0c896 to your computer and use it in GitHub Desktop.
File input form events final (article embed)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Component, ElementRef, ViewChild} from '@angular/core'; | |
import {HttpClient} from '@angular/common/http'; | |
import {environment} from '../environments/environment'; | |
@Component({ | |
selector: 'app-root', | |
templateUrl: './app.component.html', | |
styleUrls: ['./app.component.css'] | |
}) | |
export class AppComponent { | |
acceptedMimeTypes = [ | |
'image/gif', | |
'image/jpeg', | |
'image/png' | |
]; | |
@ViewChild('fileInput') fileInput: ElementRef; | |
fileDataUri = ''; | |
errorMsg = ''; | |
constructor(private http: HttpClient) {} | |
previewFile() { | |
const file = this.fileInput.nativeElement.files[0]; | |
if (file && this.validateFile(file)) { | |
const reader = new FileReader(); | |
reader.readAsDataURL(this.fileInput.nativeElement.files[0]); | |
reader.onload = () => { | |
this.fileDataUri = reader.result; | |
} | |
} else { | |
this.errorMsg = 'File must be jpg, png, or gif and cannot be exceed 500 KB in size' | |
} | |
} | |
uploadFile(event: Event) { | |
event.preventDefault(); | |
// get only the base64 file and post it | |
if (this.fileDataUri.length > 0) { | |
const base64File = this.fileDataUri.split(',')[1]; | |
const data = {'image': base64File}; | |
this.http.post(`${environment.apiUrl}/upload-photo`, data) | |
.subscribe( | |
res => { | |
// handle success | |
// reset file input | |
this.fileInput.nativeElement.value = ''; | |
}, | |
err => { | |
this.errorMsg = 'Could not upload image.'; | |
} | |
); | |
} | |
} | |
validateFile(file) { | |
return this.acceptedMimeTypes.includes(file.type) && file.size < 500000; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment