使用JavaScript / jQuery在上传时验证文件大小

使用JavaScript / jQuery在上传时验证文件大小

在本文中,我们将学习如何通过在上传之前检查文件大小来实现文件大小验证,使用Javascript和jQuery。这是客户端验证的演示,并且实现了良好的用户体验。在某些情况下,客户端验证是一种比服务器端方法更好的方法,因为它消耗的时间更少。

例如,如果我们不允许上传大于4MB或小于2MB的文件,我们可以使用客户端验证来检查用户选择的文件是否满足给定的要求,如果不满足,则给出提示信息,以免用户花费时间上传文件,只得到服务器错误。

方法1

  • 监听输入框上的change事件。
  • 检查是否选择了任何文件 files.length > 0
  • 通过 files.item(i).size 获取文件大小。
  • 该值将以字节为单位。通过 Math.round((filesize/1024)) 将其转换为所需的任何单位,例如兆字节。
  • 检查大小是否符合您的要求。

示例1: 这个示例展示了上述方法的使用。

<!DOCTYPE html>
<html>
<head>
    <title>File Validation-1</title>
</head>
 
<body>
    <p>
        <input type="file" id="file"
               onchange="Filevalidation()" />
    </p>
 
    <p id="size"></p>
 
    <script>
        Filevalidation = () => {
            const fi = document.getElementById('file');
            // Check if any file is selected.
            if (fi.files.length > 0) {
                for (const i = 0; i <= fi.files.length - 1; i++) {
         
                    const fsize = fi.files.item(i).size;
                    const file = Math.round((fsize / 1024));
                    // The size of the file.
                    if (file >= 4096) {
                        alert(
                          "File too Big, please select a file less than 4mb");
                    } else if (file < 2048) {
                        alert(
                          "File too small, please select a file greater than 2mb");
                    } else {
                        document.getElementById('size').innerHTML = '<b>'
                        + file + '</b> KB';
                    }
                }
            }
        }
    </script>
</body>
</html>

输出:

使用JavaScript / jQuery在上传时验证文件大小

方法2

在下面的示例中,我们将学习如何使用jQuery完成相同的操作。

  • 监听输入框的改变事件。
  • 通过 this.files[0].size 获取文件的大小。
  • 可以通过 toFixed() 方法将得到的值四舍五入。
  • 检查文件大小是否符合你的要求。

示例: 本示例展示了上述方法的应用。

<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type"
          content="text/html; charset=iso-8859-1" />
    <title>JQuery File Validation</title>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
    </script>
</head>
 
<body>
    <input id="file" type="file" name="file" />
    <p id="output"></p>
 
    <script type="text/javascript">
        ('#file').on('change', function() {
         
            const size = 
               (this.files[0].size / 1024 / 1024).toFixed(2);
         
            if (size>4 || size<2) {
                alert("File must be between the size of 2-4 MB");
            } else {
                ("#output").html('<b>' +
                   'This file size is: ' + size + " MB" + '</b>');
            }
        });
    </script>
</body>
</html>

输出:

使用JavaScript / jQuery在上传时验证文件大小

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程