Last active
August 29, 2015 14:12
-
-
Save bliaxiong/64abea351c1393ad3085 to your computer and use it in GitHub Desktop.
Js check upload file size
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This awesome jQuery plugin will check the file size and against the selected upload file and | |
// determine if its allowable. The size limit will have to be in bytes. | |
// Parameters: | |
// evt_type - the javascript event, if non is needed, set to empty string | |
// limit - the size limit in bytes (default javascript size measurement) | |
$.fn.fileSizeCheck = function(evt_type, limit) { | |
var sizeLimit = limit; | |
if (evt_type == "") { | |
checkSize($(this).attr('id')); | |
} else { | |
$(this).bind("" + evt_type + "", function() { | |
checkSize($(this).attr('id')); | |
}); | |
} | |
function checkSize(id) { | |
upload_id = id; | |
input = document.getElementById("" + upload_id + ""); | |
if (window.FileReader && input.files[0]) { | |
file = input.files[0]; | |
if (file.size > sizeLimit) { | |
// Clear the upload input field | |
document.getElementById(""+upload_id+"").value = ''; | |
// Generate actual size of file | |
err_msg = bytesToSize(file.size); | |
// Display warning to user | |
var warn_sg = $("#"+upload_id).next(); | |
if ($(warn_sg).attr('class') != 'file_size_warn') { | |
$("#"+upload_id).after('<span class="file_size_warn" style="color: red;">File size greater than allowed, current size: ' + err_msg + '.</span>') | |
} | |
} else { | |
// Remove warning if file meets size limit | |
var warn_sg = $("#"+upload_id).next(); | |
if ($(warn_sg).attr('class') == 'file_size_warn') { | |
$(warn_sg).remove(); | |
} | |
} | |
} | |
} | |
// http://stackoverflow.com/questions/15900485/correct-way-to-convert-size-in-bytes-to-kb-mb-gb-in-javascript | |
function bytesToSize(bytes) { | |
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; | |
if (bytes == 0) return '0 Byte'; | |
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024))); | |
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i]; | |
}; | |
}; | |
/* | |
Example usage: | |
$(".a").fileSizeCheck("change",123) | |
or | |
$(".a").fileSizeCheck("",123) | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment