1/3/2017 - 7:26 PM

File upload image with max size and file restriction

File upload image with max size and file restriction


<!DOCTYPE html>
	<meta charset=utf-8 />

	<script src="https://code.jquery.com/jquery-1.8.3.js"></script>
	<!--[if IE]>
		<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>

<input id="filelogo" type="file" ><br>
<img id="showimage" src="" height="200" alt="Image preview..."> 


$("#filelogo").change(function() {
	var preview = document.querySelector('#showimage');
	var file    = document.querySelector('input[type=file]').files[0];
	var reader = new FileReader();

	// console.log(file) ;	
    if( $('#filelogo').val() !=""){
	    // readURL function is redundant so we just use reader.onload if the file size is less than 1MB
	    // 'this'  refers to the current file object
	     // check if file size is greater than 1MB OR file is not an image
        if (file.size>=1000000 || file['type'].split('/')[0] !='image'  ) {
	        alert("File Size is more than 1MB OR File is not an image") ;
        else {  
			reader.addEventListener("load", function () {
			    preview.src = reader.result;
			}, false);	        
			if ( file ) {   reader.readAsDataURL(file);    }

    /* optional 
    else {
	    // triggers when a file selection is cancelled or there is no image currently selected
	    console.log("File selection cancelled, loading default placeholder.png") ;