105

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

Yuck
  • 49,664
  • 13
  • 105
  • 135
Nisanth Kumar
  • 5,667
  • 8
  • 33
  • 43
  • 2
    and obviously duplicate of http://stackoverflow.com/search?q=file+size+before+upload – Your Common Sense Sep 21 '11 at 09:22
  • 1
    possible duplicate of [How to check file input size with jQuery?](http://stackoverflow.com/questions/1601455/how-to-check-file-input-size-with-jquery) – L84 Jun 01 '15 at 16:11
  • Possible duplicate of [JavaScript file upload size validation](http://stackoverflow.com/questions/3717793/javascript-file-upload-size-validation) – Frank Tan Sep 19 '16 at 15:42

14 Answers14

151

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?

Community
  • 1
  • 1
Brij
  • 6,086
  • 9
  • 41
  • 69
  • 1
    Isn't the files array non-existent on internet explorer (older versions)? – Tiago César Oliveira Apr 18 '13 at 14:26
  • 4
    Yes, this does not work pre IE 10 and only has partial support in android and ios. http://caniuse.com/fileapi. If it were only this easy... – styks May 30 '13 at 14:48
  • 3
    I suppose the result is in bytes? – Erdal G. May 13 '16 at 12:00
  • 5
    @ErdalG. Good question! MDN is [missing](https://developer.mozilla.org/en-US/docs/Web/API/File/size) the documentation, but `FileList.files` is an array-like of `File` objects, which is an extension of `Glob`. And [according to the spec](https://w3c.github.io/FileAPI/#attributes-blob), `Glob` indeed defines the `size` property as the number of _bytes_ (0 for an empty file). So yes, **the result is in bytes**. – John Weisz Jan 27 '17 at 15:36
15
<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

Behnam Bakhshi
  • 263
  • 2
  • 6
  • 16
    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 Jan 30 '15 at 22:41
  • 3
    I like this solution, because only older versions of IE will return true for window.ActiveXObject. – Rob Breidecker Jun 04 '15 at 16:36
  • 3
    @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. – Nicolas Bouvrette Jun 25 '17 at 19:43
  • @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. – scott stone Jun 28 '17 at 23:15
  • @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. – Nicolas Bouvrette Jul 03 '17 at 15:25
  • Thanks for your answer. May I ask a question about your solution please? I notice if I use ``, the function works. However, if I change to ``, the function will not work. Would you mind let me know my mistake please? Thank you very much. – Learner Oct 06 '17 at 08:30
  • I tried to change `function AlertFilesize(){` to `function AlertFilesize(value){` and then change`` to ``, but still not working. – Learner Oct 06 '17 at 08:37
  • I think, it shoud be: parseFloat(Math.floor(fSize*100)/100) +''+fSExt[i]; – Hoàng Vũ Tgtt May 06 '20 at 16:57
15

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.

Gleb Kemarsky
  • 10,160
  • 7
  • 43
  • 68
jaggedsoft
  • 3,858
  • 2
  • 33
  • 41
9

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.

Hoang Le
  • 1,341
  • 14
  • 14
  • 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 :) – Matt Oct 15 '17 at 20:27
9

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;
}
Warren Sergent
  • 2,542
  • 4
  • 36
  • 42
ucefkh
  • 2,509
  • 2
  • 22
  • 18
  • 3
    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 Jan 30 '15 at 22:42
  • 1
    $.browser was removed from jQuery in version 1.9 (deprecated since v 1.3). – Silvio Delgado Mar 21 '15 at 20:08
  • 2
    @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 http://www.computerworld.com/article/2481188/internet/why-microsoft-won-t-abandon-internet-explorer.html – ucefkh Mar 23 '15 at 16:55
  • @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) – ucefkh Mar 23 '15 at 17:03
8

$(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>
Viraj Nalawade
  • 3,137
  • 3
  • 28
  • 44
vishay hard
  • 81
  • 1
  • 2
4

Browsers with HTML5 support has files property for input type. This will of course not work in older IE versions.

var inpFiles = document.getElementById('#fileID');
for (var i = 0; i < inpFiles.files.length; ++i) {
    var size = inpFiles.files.item(i).size;
    alert("File Size : " + size);
}
Sandeep G
  • 371
  • 1
  • 4
  • 10
3

Please do not use ActiveX as chances are that it will display a scary warning message in Internet Explorer and scare your users away.

ActiveX warning

If anyone wants to implement this check, they should only rely on the FileList object available in modern browsers and rely on server side checks only for older browsers (progressive enhancement).

function getFileSize(fileInputElement){
    if (!fileInputElement.value ||
        typeof fileInputElement.files === 'undefined' ||
        typeof fileInputElement.files[0] === 'undefined' ||
        typeof fileInputElement.files[0].size !== 'number'
    ) {
        // File size is undefined.
        return undefined;
    }

    return fileInputElement.files[0].size;
}
Nicolas Bouvrette
  • 4,295
  • 1
  • 39
  • 53
2

ucefkh's solution worked best, but because $.browser was deprecated in jQuery 1.91, had to change to use navigator.userAgent:

function IsFileSizeOk(fileid) {
    try {
        var fileSize = 0;
        //for IE
        if (navigator.userAgent.match(/msie/i)) {
            //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 
        }
        return (fileSize < 2.0);
    }
    catch (e) {
        alert("Error is :" + e);
    }
}
Warren Sergent
  • 2,542
  • 4
  • 36
  • 42
Mike
  • 629
  • 5
  • 18
1

Get the size of the file by files.item(i).size.

You should try this.
https://www.geeksforgeeks.org/validation-of-file-size-while-uploading-using-javascript-jquery/

1

you need to do an ajax HEAD request to get the filesize. with jquery it's something like this

  var req = $.ajax({
    type: "HEAD",
    url: yoururl,
    success: function () {
      alert("Size is " + request.getResponseHeader("Content-Length"));
    }
  });
kasper Taeymans
  • 6,950
  • 5
  • 32
  • 51
0

Personally, I would say Web World's answer is the best today, given HTML standards. If you need to support IE < 10, you will need to use some form of ActiveX. I would avoid the recommendations that involve coding against Scripting.FileSystemObject, or instantiating ActiveX directly.

In this case, I have had success using 3rd party JS libraries such as plupload which can be configured to use HTML5 apis or Flash/Silverlight controls to backfill browsers that don't support those. Plupload has a client side API for checking file size that works in IE < 10.

Community
  • 1
  • 1
scott stone
  • 439
  • 5
  • 8
0

You can use PHP filesize function. During upload using ajax, please check the filesize first by making a request an ajax request to php script that checks the filesize and return the value.

rechie
  • 2,139
  • 5
  • 25
  • 38
0

You can by using HTML5 File API: http://www.html5rocks.com/en/tutorials/file/dndfiles/

However you should always have a fallback for PHP (or any other backend language you use) for older browsers.

José P. Airosa
  • 368
  • 1
  • 2
  • 11