Get file size before uploading

264,510

Solution 1

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:

How to check file input size with jQuery?

Solution 2

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.

Solution 3

<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

Solution 4

I had the same problem and seems like we haven't had an accurate solution. Hope this can help other people.

After take time exploring around, I finally found the answer. This is my code to get file attach with jQuery:

var attach_id = "id_of_attachment_file";
var size = $('#'+attach_id)[0].files[0].size;
alert(size);

This is just the example code for getting the file size. If you want do other stuffs, feel free to change the code to satisfy your needs.

Solution 5

Best solution working on all browsers ;)

function GetFileSize(fileid) {
    try {
        var fileSize = 0;
        // for IE
        if(checkIE()) { //we could use this $.browser.msie but since it's deprecated, we'll use this function
            // before making an object of ActiveXObject, 
            // please make sure ActiveX is enabled in your IE browser
            var objFSO = new ActiveXObject("Scripting.FileSystemObject");
            var filePath = $("#" + fileid)[0].value;
            var objFile = objFSO.getFile(filePath);
            var fileSize = objFile.size; //size in b
            fileSize = fileSize / 1048576; //size in mb 
        }
        // for FF, Safari, Opeara and Others
        else {
            fileSize = $("#" + fileid)[0].files[0].size //size in b
            fileSize = fileSize / 1048576; //size in mb 
        }
        alert("Uploaded File Size is" + fileSize + "MB");
    }
    catch (e) {
        alert("Error is :" + e);
    }
}

from http://www.dotnet-tricks.com/Tutorial/jquery/HHLN180712-Get-file-size-before-upload-using-jquery.html

UPDATE : We'll use this function to check if it's IE browser or not

function checkIE() {
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)){  
        // If Internet Explorer, return version number
        alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
    } else {
        // If another browser, return 0
        alert('otherbrowser');
    }

    return false;
}
Share:
264,510
Nisanth Kumar
Author by

Nisanth Kumar

Chief Technical Architect iTraveller Technologies Pvt Ltd India (PHP) (CakePHP) (jQuery) (MySQL) (Zend Framework) (HTML5) (CSS) (API) :)

Updated on October 19, 2020

Comments

  • Nisanth Kumar
    Nisanth Kumar over 3 years

    Is there any way to find out the file size before uploading the file using AJAX / PHP in change event of input file?

  • Tiago César Oliveira
    Tiago César Oliveira about 11 years
    Isn't the files array non-existent on internet explorer (older versions)?
  • styks
    styks about 11 years
    Yes, this does not work pre IE 10 and only has partial support in android and ios. caniuse.com/fileapi. If it were only this easy...
  • DeLe
    DeLe almost 11 years
    But if do that file input will clear(empty) ?? Can u make a example thank
  • scott stone
    scott stone over 9 years
    downvoted because the answer uses ActiveX. in 2015, even Microsoft is abandoning ActiveX. While it was a reasonable suggestion when given, I would recommend developers avoid this now and in the future.
  • scott stone
    scott stone over 9 years
    downvoted because the answer uses ActiveX. in 2015, even Microsoft is abandoning ActiveX. While it was a reasonable suggestion when given, I would recommend developers avoid this now and in the future. –
  • Silvio Delgado
    Silvio Delgado about 9 years
    $.browser was removed from jQuery in version 1.9 (deprecated since v 1.3).
  • ucefkh
    ucefkh about 9 years
    @scottstone this is for backward compability and that's not true Microsoft won't abdon ActiveX it is to much used in many things and here is the proof computerworld.com/article/2481188/internet/…
  • ucefkh
    ucefkh about 9 years
    @SilvioDelgado Changed and updated they removed $.browser into a plugin so we'll need just a small test for IE browser (works with all versions)
  • Rob Breidecker
    Rob Breidecker almost 9 years
    I like this solution, because only older versions of IE will return true for window.ActiveXObject.
  • Erdal G.
    Erdal G. about 8 years
    I suppose the result is in bytes?
  • John Weisz
    John Weisz over 7 years
    @ErdalG. Good question! MDN is missing the documentation, but FileList.files is an array-like of File objects, which is an extension of Glob. And according to the spec, Glob indeed defines the size property as the number of bytes (0 for an empty file). So yes, the result is in bytes.
  • Nicolas Bouvrette
    Nicolas Bouvrette almost 7 years
    @scottstone I don't understand why you down voted all answers supporting legacy browsers? This answer is much cleaner than the ones using browser fingerprints and by no means recommand anyone to use ActiveX.
  • scott stone
    scott stone almost 7 years
    @NicolasBouvrette - I agree that this answer is much cleaner than the others, but I can't remove the downvote at this point. The original question did not ask for compatibility with old versions of IE, and this answer doesn't advise readers that most of the code is there to support 5+ year old versions of IE.
  • Nicolas Bouvrette
    Nicolas Bouvrette almost 7 years
    @scottstone Actually one more tangible point from my view on why not to use ActiveX is because it displays a warning message in IE which is an horrible (scary?) user experience.
  • Learner
    Learner over 6 years
    Thanks for your answer. May I ask a question about your solution please? I notice if I use <input id="fileInput" type="file" onchange="AlertFilesize();" />, the function works. However, if I change to <s:file name="upload"size="30" label="Upload" id="fileInput" onchange="AlertFilesize();"/>, the function will not work. Would you mind let me know my mistake please? Thank you very much.
  • Learner
    Learner over 6 years
    I tried to change function AlertFilesize(){ to function AlertFilesize(value){ and then change<input id="fileInput" type="file" onchange="AlertFilesize();" /> to <s:file name="upload"size="30" label="Upload" id="fileInput" onchange="AlertFilesize(this.value);"/>, but still not working.
  • Matt
    Matt over 6 years
    I like this one because it doesn't need to be put on the change event like the most popular solution. And I also like the fact you have given me permission to change the code to satisfy my needs :)
  • Hoàng Vũ Tgtt
    Hoàng Vũ Tgtt about 4 years
    I think, it shoud be: parseFloat(Math.floor(fSize*100)/100) +''+fSExt[i];