Is there any way to check file size before uploading it using JavaScript?
Using jquery:
<form action="upload" enctype="multipart/form-data" method="post">
Upload image:
<input id="image-file" type="file" name="file" />
<input type="submit" value="Upload" />
<script type="text/javascript">
$('#image-file').bind('change', function() {
alert('This file size is: ' + this.files[0].size/1024/1024 + "MB");
});
</script>
</form>
I use one main Javascript function that I had found at Mozilla Developer Network site https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications, along with another function with AJAX and changed according to my needs. It receives a document element id regarding the place in my html code where I want to write the file size.
<Javascript>
function updateSize(elementId) {
var nBytes = 0,
oFiles = document.getElementById(elementId).files,
nFiles = oFiles.length;
for (var nFileId = 0; nFileId < nFiles; nFileId++) {
nBytes += oFiles[nFileId].size;
}
var sOutput = nBytes + " bytes";
// optional code for multiples approximation
for (var aMultiples = ["K", "M", "G", "T", "P", "E", "Z", "Y"], nMultiple = 0, nApprox = nBytes / 1024; nApprox > 1; nApprox /= 1024, nMultiple++) {
sOutput = " (" + nApprox.toFixed(3) + aMultiples[nMultiple] + ")";
}
return sOutput;
}
</Javascript>
<HTML>
<input type="file" id="inputFileUpload" onchange="uploadFuncWithAJAX(this.value);" size="25">
</HTML>
<Javascript with XMLHttpRequest>
document.getElementById('spanFileSizeText').innerHTML=updateSize("inputFileUpload");
</XMLHttpRequest>
Cheers
I ran across this question, and the one line of code I needed was hiding in big blocks of code.
Short answer: this.files[0].size
By the way, no JQuery needed.
No Yes, using the File API in newer browsers. See TJ's answer for details.
If you need to support older browsers as well, you will have to use a Flash-based uploader like SWFUpload or Uploadify to do this.
The SWFUpload Features Demo shows how the file_size_limit
setting works.
Note that this (obviously) needs Flash, plus the way it works is a bit different from normal upload forms.
If you're using jQuery Validation, you could write something like this:
$.validator.addMethod(
"maxfilesize",
function (value, element) {
if (this.optional(element) || ! element.files || ! element.files[0]) {
return true;
} else {
return element.files[0].size <= 1024 * 1024 * 2;
}
},
'The file size can not exceed 2MB.'
);
It's pretty simple.
var oFile = document.getElementById("fileUpload").files[0]; // <input type="file" id="fileUpload" accept=".jpg,.png,.gif,.jpeg"/>
if (oFile.size > 2097152) // 2 mb for bytes.
{
alert("File size must under 2mb!");
return;
}