jquery - 使用 jQuery 验证上传中的文件大小
问题描述
我正在尝试在我的 ASP.NET 应用程序的文件上传控件中验证文件大小,甚至在单击提交按钮之前。
我的最大值。大小为 20kB。
当我单击按钮时 - 即使文件小于最大大小 - 它仍然向我显示消息
文件大小应小于 20kb
您可以在下面找到相应的代码:
<script type="text/javascript">
$(document).ready(function () {
$('#AdmissionUpload').on('change', function() {
// Maximum file size allowed
var maxFileSize = 20 // 20kb
// Load the file upload controller to a variable
var fileUpload = $('#AdmissionUpload');
//Check if the file upload controller has value
if (fileUpload.val() == '') {
return false;
} else {
//Check if the file size is less than maximum file size
if (fileUpload[0].files[0].size < maxFileSize) {
return true;
} else {
alert('File size should be less than 20kb')
fileUpload.val('');
return false;
}
}
});
})
</script>
解决方案
改变
if (fileUpload[0].files[0].size < maxFileSize) {
return true;
} else {
alert('File size should be less than 20kb')
fileUpload.val('');
return false;
}
至
var size = parseFloat(fileUpload[0].files[0].size / 1024).toFixed(2);
//Check if the file size is less than maximum file size
if (size < maxFileSize) {
return true;
} else {
alert('File size should be less than 20kb')
fileUpload.val('');
return false;
}
推荐阅读
- linux - 主机内存不足,JVM使用稳定
- apache - 如何在 Windows 服务器中将 Apache 设置为 odoo11 的反向代理?这可能吗?
- javascript - 在 div 中显示 img ALT 文本
- laravel - 上传图像时使用 Laravel 从 dropzone 获取名称属性
- javascript - 有条件返回
- pywinauto - 自动化其小部件描述被部分填充的应用程序
- java - 在grails中编写带有加密的excel文件
- mysql - mysql - 显示按时间排序的用户列表
- python - ForeignKey 列本身的 SET_DEFAULT
- javascript - 如何在 iframe 之外获取元素