How to check file input size with jQuery?
Asked Answered
G

10

152

I have a form with file upload capabilities and I would like to be able to have some nice client side error reporting if the file the user is trying to upload is too big, is there a way to check against file size with jQuery, either purely on the client or somehow posting the file back to the server to check?

Gentilesse answered 21/10, 2009 at 15:5 Comment(0)
B
305

You actually don't have access to filesystem (for example reading and writing local files), however, due to HTML5 File Api specification, there are some file properties that you do have access to, and the file size is one of them.

For the HTML below

<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);

});

As it is a part of the HTML5 specification, it will only work for modern browsers (v10 required for IE) and I added here more details and links about other file information you should know: http://felipe.sabino.me/javascript/2012/01/30/javascipt-checking-the-file-size/


Old browsers support

Be aware that old browsers will return a null value for the previous this.files call, so accessing this.files[0] will raise an exception and you should check for File API support before using it

Bissau answered 14/10, 2010 at 20:46 Comment(10)
Everyone says this can't be done - yet here it is. This works. I tested it.Dichlorodifluoromethane
@Jeroen I agree that not working for IE makes it not the ideal solution for a lot of people, but isn't giving a down-vote and saying the answer is useless a bit too much? I used this solution in a great variety of enterprise web solutions that had in the scope the need to work only in chrome and/or firefox, and some people looking for this solution might be in the same spot, so this solution will be good enough.Bissau
I've just come across this answer on Google and am going to use it to stop users posting files which are over a given size; as I also check file sizes on the server side I'm happy to have a client-side solution which doesn't work in IE8.Philbin
@GaolaiPeng This error is probably because the jQuery javascript file was not added (or it was not loaded properly). Do you have it added in the head of your page?Bissau
As with most of the modern web it doesn't at all surprise me that it doesn't work on an antiquated browser like IE8… however… what happens when you do attempt to use it? Does it just return a null value? Does it cause the script to fail? I think this is a more important angle than simply whether it works or not.Spongin
Does this mean that non-HTML5 browsers cannot show the file size? It may ruin the UI in that case and tell the user they're uploading a file of null size. This would confuse them into thinking they're uploading nothing!!Veneaux
@volumeone That's why I said you should "check for File API support before using it" in my answer and then you could change the UI accordingly.Bissau
For old IE you can send file in background to server right after it added to input, calculate size there and send response back.(github.com/malsup/form can do it using iframe) But if you have dominant position over your clients (like you are big company and clients are tied to you), then you don't need to waste your resources supporting theirs outdated browser.Zwiebel
Of course, you don't have to bind the file input field to an event and access the file object directly. For example: document.getElementById("myfile").files[0].size. In addition, it is best practice to make sure there is a selected file in the field BEFORE running this kind of code directly on it...Briefs
worked for me. @section Scripts { @{ await Html.RenderPartialAsync("_ValidationScriptsPartial");} <script> $('#file1').bind('change', function () { //this.files[0].size gets the size of your file. alert(this.files[0].size); }); </script> }Larianna
S
48

If you want to use jQuery's validate you can by creating this method:

$.validator.addMethod('filesize', function(value, element, param) {
    // param = size (en bytes) 
    // element = element to validate (<input>)
    // value = value of the element (file name)
    return this.optional(element) || (element.files[0].size <= param) 
});

You would use it:

$('#formid').validate({
    rules: { inputimage: { required: true, accept: "png|jpe?g|gif", filesize: 1048576  }},
    messages: { inputimage: "File must be JPG, GIF or PNG, less than 1MB" }
});
Sashenka answered 7/9, 2011 at 21:55 Comment(3)
@Dan yes, the file size property is a part of the HTML5 specification, so it will only work for modern browsers (for IE it would be version 10+)Bissau
You've incorrectly used the accept rule, where you should have used the extension rule. ~ The accept rule is only for MIME types. The extension rule is for file extensions. You also need to include the additional-methods.js file for these rules.Sundog
Complementing @Sparky's assertive comment: $('#formid').validate({ rules: { inputimage: { required: true, extension: "png|jpe?g|gif", filesize: 1048576 }}, messages: { inputimage: "File must be JPG, GIF or PNG, less than 1MB" } });Euthenics
T
33

This code:

$("#yourFileInput")[0].files[0].size;

Returns the file size for an form input.

On FF 3.6 and later this code should be:

$("#yourFileInput")[0].files[0].fileSize;
Trousers answered 9/3, 2012 at 20:13 Comment(3)
Your fist code works in chrome but second doesn't work for FireFox latest.Subaxillary
That second code is what I had to use for all modern (2014+ browsers).Kianakiang
The first code works IE 10, 11, Edge, Chrome, Safari(Windows version), Brave and Firefox.Coolish
R
19

Use below to check file's size and clear if it's greater,

    $("input[type='file']").on("change", function () {
     if(this.files[0].size > 2000000) {
       alert("Please upload file less than 2MB. Thanks!!");
       $(this).val('');
     }
    });
Riobard answered 20/10, 2018 at 10:7 Comment(1)
Should use $(this).val(null); Otherwise the form does not seem to submit correctly anymore without selecting a proper attachment.Namecalling
H
14

I am posting my solution too, used for an ASP.NET FileUpload control. Perhaps someone will find it useful.

    $(function () {        
    $('<%= fileUploadCV.ClientID %>').change(function () {

        //because this is single file upload I use only first index
        var f = this.files[0]

        //here I CHECK if the FILE SIZE is bigger than 8 MB (numbers below are in bytes)
        if (f.size > 8388608 || f.fileSize > 8388608)
        {
           //show an alert to the user
           alert("Allowed file size exceeded. (Max. 8 MB)")

           //reset file upload control
           this.value = null;
        }
    })
});
Hentrich answered 24/12, 2014 at 9:37 Comment(1)
You need to null-check the value of f = this.files[0] or this will fail on older browsers. e.g. if (f && (f.size > 8388608 || f.fileSize > 8388608))Javierjavler
G
3
<form id="uploadForm" class="disp-inline" role="form" action="" method="post" enctype="multipart/form-data">
    <input type="file" name="file" id="file">
</form>
<button onclick="checkSize();"></button>
<script>
    function checkSize(){
        var size = $('#uploadForm')["0"].firstChild.files["0"].size;
        console.log(size);
    }
</script>

I found this to be the easiest if you don't plan on submitted the form through standard ajax / html5 methods, but of course it works with anything.

NOTES:

var size = $('#uploadForm')["0"]["0"].files["0"].size;

This used to work, but it doesn't in chrome anymore, i just tested the code above and it worked in both ff and chrome (lastest). The second ["0"] is now firstChild.

Garver answered 11/4, 2017 at 4:40 Comment(0)
G
3

Plese try this:

var sizeInKB = input.files[0].size/1024; //Normally files are in bytes but for KB divide by 1024 and so on
var sizeLimit= 30;

if (sizeInKB >= sizeLimit) {
    alert("Max file size 30KB");
    return false;
}
Geanticlinal answered 6/8, 2018 at 11:28 Comment(0)
M
2

You can do this type of checking with Flash or Silverlight but not Javascript. The javascript sandbox does not allow access to the file system. The size check would need to be done server side after it has been uploaded.

If you want to go the Silverlight/Flash route, you could check that if they are not installed to default to a regular file upload handler that uses the normal controls. This way, if the do have Silverlight/Flash installed their experience will be a bit more rich.

Moberg answered 21/10, 2009 at 15:17 Comment(0)
I
0

HTML code:

<input type="file" id="upload" class="filestyle" onchange="SizeCheck();"/>

JavaScript Function:

function SizeCheck() {
            var fileInput = document.getElementById('upload').files;
            var fsize = fileInput[0].size;
            var file = Math.round((fsize / 1024));
            if (file >= 10240) {     //10MB
               //Add Alert Here If 
                $('#upload_error').html("* File Size < 10MB");
            }
            else {
                $('#invoice_error').html("");
            }
        }
Involucel answered 25/7, 2022 at 12:33 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Didactic
F
0
<script>
  if (Math.round((document.getElementById('Your_input_id').files[0].size / 1024)>= 1024) { //2MB
    $("#your_error_id").html("File Size < 1MB");
    $("#your_error_id").css("color", "#dd4b39");
    $("#Your_input_id").val('');
    return false;
  }
</script>
Frasier answered 16/1, 2023 at 13:13 Comment(1)
Your answer could be improved by adding more information on what the code does and how it helps the OP.Auston

© 2022 - 2024 — McMap. All rights reserved.