How to check file input size with jQuery?
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开发者_如何学JAVA 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?
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
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" }
});
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;
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('');
}
});
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;
}
})
});
<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.
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;
}
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.
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("");
}
}
精彩评论