Skip to content

Instantly share code, notes, and snippets.

@mmccall10
Created September 26, 2017 05:45
Show Gist options
  • Select an option

  • Save mmccall10/a0cd52b539ec51b7ca14b33f7c9e2348 to your computer and use it in GitHub Desktop.

Select an option

Save mmccall10/a0cd52b539ec51b7ca14b33f7c9e2348 to your computer and use it in GitHub Desktop.

Revisions

  1. mmccall10 created this gist Sep 26, 2017.
    50 changes: 50 additions & 0 deletions app.component.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    import {Component, ElementRef, ViewChild} from '@angular/core';

    @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 = '';

    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
    if (this.fileDataUri.length > 0) {
    const base64File = this.fileDataUri.split(',')[1];
    // TODO: send to server
    console.log(base64File);
    }

    }

    validateFile(file) {
    return this.acceptedMimeTypes.includes(file.type) && file.size < 500000;
    }

    }