jcadima
6/27/2017 - 3:10 PM

File Upload Image Preview

File Upload Image Preview


https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL

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

	<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>
	<![endif]-->
</head>
<body>

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


<script>
$("#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") ;
	    $('#showimage').attr('src','https://regigo.com/beta/organizer/images/placeholder.png');
	}  
	*/  
});

</script>

</html>