Last active
December 27, 2018 09:37
-
-
Save StefanNieuwenhuis/0f5cbd5cb2a102d08792370892c876df to your computer and use it in GitHub Desktop.
This file contains 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 } from '@stencil/core'; | |
const MAX_UPLOAD_SIZE = 1024; // bytes | |
const ALLOWED_FILE_TYPES = 'image.*'; | |
@Component({ | |
tag: 'my-component', | |
styleUrl: 'my-component.css', | |
shadow: true | |
}) | |
export class MyComponent { | |
public onInputChange(files: FileList) { | |
// check if 1 image is uploaded | |
if (files.length === 1) { | |
const imageFile = files[0]; | |
// check if the user isn't trying to upload a file larger then the MAX_UPLOAD_SIZE | |
if (!this.checkFileSize(imageFile.size)) { | |
console.error('Maximum file size exceeded. Max file size is: ' + MAX_UPLOAD_SIZE); | |
return false; | |
} | |
// check if the user isn't trying to upload anything else then an image | |
else if (!this.checkFileType(imageFile.type)) { | |
console.error('File type is not allowed'); | |
return false; | |
} | |
}else{ | |
console.error(files.length === 0 ? 'NO IMAGE UPLOADED' : 'YOU CAN ONLY UPLOAD ONE IMAGE AT THE TIME'); | |
return false; | |
} | |
} | |
private checkFileSize(size: number): boolean { | |
return (size / MAX_UPLOAD_SIZE / MAX_UPLOAD_SIZE) <= MAX_UPLOAD_SIZE; | |
} | |
private checkFileType(type: string): boolean { | |
return type.match(ALLOWED_FILE_TYPES).length > 0; | |
} | |
render() { | |
return <div class="image-upload"> | |
<div class="image-upload__edit"> | |
<label htmlFor="file"></label> | |
<input type="file" name="files[]" id="file" accept="image/*" class="image-upload__input" | |
onChange={($event: any) => this.onInputChange($event.target.files)} /> | |
</div> | |
<div class="image-upload__preview"> | |
<div id="image-preview"></div> | |
</div> | |
</div>; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment