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?
10 Answers
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

- 1
- 1

- 17,825
- 6
- 78
- 112
-
8Everyone says this can't be done - yet here it is. This works. I tested it. – Peter Jan 11 '11 at 16:24
-
35@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. – Felipe Sabino Aug 03 '11 at 22:08
-
4I'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. – Steve Wilkes Aug 16 '11 at 14:54
-
2@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? – Felipe Sabino Jan 19 '12 at 22:06
-
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. – Nathan Hornby Mar 05 '14 at 14:09
-
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!! – volume one Oct 13 '15 at 14:28
-
1@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. – Felipe Sabino Oct 15 '15 at 17:50
-
For old IE you can send file in background to server right after it added to input, calculate size there and send response back.(https://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. – Andrei Nov 16 '16 at 09:25
-
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... – TheCuBeMan Jan 26 '17 at 17:27
-
worked for me. @section Scripts { @{ await Html.RenderPartialAsync("_ValidationScriptsPartial");} } – Brian Bird Apr 19 '22 at 19:16
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" }
});

- 8,793
- 4
- 49
- 65
-
1@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+) – Felipe Sabino Jan 17 '14 at 17:12
-
7You've incorrectly used the `accept` rule, where you should have used the `extension` rule. ~ [The `accept` rule](http://jqueryvalidation.org/accept-method/) is only for MIME types. [The `extension` rule](http://jqueryvalidation.org/extension-method/) is for file extensions. You also need to include [the `additional-methods.js` file](http://cdn.jsdelivr.net/jquery.validation/1.13.1/additional-methods.js) for these rules. – Sparky Jun 04 '15 at 17:54
-
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" } });` – victorf Aug 07 '15 at 13:46
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;

- 441
- 4
- 3
-
2Your fist code works in chrome but second doesn't work for FireFox latest. – Débora Apr 23 '12 at 15:20
-
That second code is what I had to use for all modern (2014+ browsers). – Dreamcasting Jan 28 '16 at 21:52
-
1The first code works IE 10, 11, Edge, Chrome, Safari(Windows version), Brave and Firefox. – Mashukur Rahman Jun 13 '19 at 10:48
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('');
}
});

- 4,668
- 32
- 24
-
1Should use $(this).val(null); Otherwise the form does not seem to submit correctly anymore without selecting a proper attachment. – Kevin Grabher Apr 22 '19 at 20:30
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;
}
})
});

- 819
- 8
- 6
-
1You 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))` – iCollect.it Ltd Oct 03 '16 at 10:18
<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.

- 473
- 4
- 11
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;
}

- 4,412
- 5
- 49
- 64
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.

- 47,246
- 16
- 124
- 162
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("");
}
}
-
1Your 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](/help/how-to-answer). – Community Jul 26 '22 at 09:02
<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>

- 2,324
- 26
- 22
- 31

- 1
- 2
-
1Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Jan 17 '23 at 19:28