首页 > 解决方案 > 使用 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>

标签: jqueryhtmljquery-file-upload

解决方案


改变

            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;
                }

推荐阅读