Get file size before uploading
For the HTML bellow
<input type="file" id="myFile" />
try the following:
//binds to onchange event of your input field$('#myFile').bind('change', function() { //this.files[0].size gets the size of your file. alert(this.files[0].size);});
See following thread:
Here's a simple example of getting the size of a file before uploading. It's using jQuery to detect whenever the contents are added or changed, but you can still get files[0].size
without using jQuery.
$(document).ready(function() { $('#openFile').on('change', function(evt) { console.log(this.files[0].size); });});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><form action="upload.php" enctype="multipart/form-data" method="POST" id="uploadform"> <input id="openFile" name="img" type="file" /></form>
Here's a more complete example, some proof of concept code to Drag and Drop files into FormData and upload via POST to a server. It includes a simple check for file size.
<script type="text/javascript">function AlertFilesize(){ if(window.ActiveXObject){ var fso = new ActiveXObject("Scripting.FileSystemObject"); var filepath = document.getElementById('fileInput').value; var thefile = fso.getFile(filepath); var sizeinbytes = thefile.size; }else{ var sizeinbytes = document.getElementById('fileInput').files[0].size; } var fSExt = new Array('Bytes', 'KB', 'MB', 'GB'); fSize = sizeinbytes; i=0;while(fSize>900){fSize/=1024;i++;} alert((Math.round(fSize*100)/100)+' '+fSExt[i]);}</script><input id="fileInput" type="file" onchange="AlertFilesize();" />
Work on IE and FF