限制文件上传的大小(html输入元素)


77

我只想限制用户可以上传的文件的大小。

我以为maxlength = 20000 = 20k,但这似乎根本不起作用。

我在Rails上运行,而不是在PHP上运行,但我认为在HTML / CSS客户端进行此操作要简单得多,或者作为最后一种使用jQuery的方法。这是如此基本,尽管必须有一些我遗漏或不知道的HTML标记。

希望支持IE7 +,Chrome,FF3.6 +。我想我可以在需要时仅支持IE8 +。

谢谢。


1
有可能的。请参考这个问题。
sandSK 2014年

Answers:


97

这是完全可能的。使用Javascript。

我使用jQuery选择输入元素。我设置了一个on change事件。

$("#aFile_upload").on("change", function (e) {

    var count=1;
    var files = e.currentTarget.files; // puts all files into an array

    // call them as such; files[0].size will get you the file size of the 0th file
    for (var x in files) {

        var filesize = ((files[x].size/1024)/1024).toFixed(4); // MB

        if (files[x].name != "item" && typeof files[x].name != "undefined" && filesize <= 10) { 

            if (count > 1) {

                approvedHTML += ", "+files[x].name;
            }
            else {

                approvedHTML += files[x].name;
            }

            count++;
        }
    }
    $("#approvedFiles").val(approvedHTML);

});

上面的代码在提交实际发生之前,将我认为值得保留的所有文件名保存到提交页面。我使用jQuery将“批准的”文件添加到输入元素的val中,以便表单提交将发送我要保存的文件的名称。所有文件都将被提交,但是,现在在服务器端,我们必须将它们过滤掉。我还没有为此编写任何代码,但是请发挥您的想象力。我假设可以通过一个for循环并匹配从输入字段发送来的名称并将它们与$ _FILES(PHP Superglobal,抱歉,我不知道ruby file variable)变量相匹配来完成此操作。

我的意思是,您可以在提交文件之前检查文件。我这样做,然后在用户提交表单之前将其输出给用户,以使他们知道他们要上传到我的网站的内容。任何不符合条件的内容都不会显示给用户,因此他们应该知道,不会保存太大的文件。这应该适用于所有浏览器,因为我没有使用FormData对象。


21
您不能在客户端执行此操作,并且期望它始终运行。如果也很重要,请在服务器端进行检查,否则人们将使用表单的修改后的副本(或其他客户端方法)来上传超大文件。服务器端检查就像锁一样,客户端检查就像贴上“保持警惕”的便条。首先将门锁上,然后竖起“注意”标志。
user340140'2013-10-9

2
@ user340140只要客户端支持javascript就可以。如果客户端不只是简单说明该站点要求启用javascript。Javascript具有一个基本上不能被欺骗的文件读取器,它可以一点一点地读取,因此不必担心会收到一个秘密地具有另一个大小的小文件。服务器端是首选的“安全”方法,但是在讨论文件大小时,我看不出JavaScript如何不那么安全。
mark.inman

6
因为就像user340140所说的,无论您做什么,都可以轻松地修改Javascript。您可以在服务器端进行可用性检查,但是不能使用客户端Javascript保护它。
Sinan Samet 2014年

仅使用JavaScript(客户端)代码是不可行的,因为可以轻松地绕开它。需要服务器端逻辑。
Akshay Anurag,

76
var uploadField = document.getElementById("file");

uploadField.onchange = function() {
    if(this.files[0].size > 2097152){
       alert("File is too big!");
       this.value = "";
    };
};

这个例子应该可以正常工作。我将其设置为大约2MB,1MB(以字节为单位)为1,048,576,因此您可以将其乘以所需的限制。

这是jsfiddle示例,更加清晰:https ://jsfiddle.net/7bjfr/808/


仅使用JavaScript(客户端)代码是不可行的,因为可以轻松地绕开它。需要服务器端逻辑。
Akshay Anurag,

6
@AkshayAnurag客户端验证防止浪费服务器的客户端和带宽的时候,它不是关于安全方面的有关UX
阿拉什Moosapour

安全从未比UX更重要。如果限制文件大小很重要,请在后端进行操作。如果您真的想在前端执行此操作,则可以使用更好的方法。
Akshay Anurag,

12
@AkshayAnurag,您只能在上传整个图像后检查后端的图像大小,如果这是一个巨大的图像,可以说16mb,并且客户端连接速度较慢,而用户必须等待整个图像上传期间才能获得一个最后的错误。为了防止类似的事情,您需要在前端进行某种形式的验证。如果我错了或者错过了一些东西,或者也许您有什么可以防止这种情况,请告诉我。
Haseeb Rehman

27

您不能在客户端这样做。您必须在服务器上执行此操作。

编辑:这个答案已经过时了!

在进行此编辑时,所有主要浏览器现在都支持HTML文件API 。

我将提供解决方案的更新,但是@ mark.inman.winning已经做到了

请记住,即使现在可以在客户端上进行验证,但是仍然应该在服务器上进行验证。可以绕过所有客户端验证。


2
是的,现在不可能。HTML5中有一些新文件api的草稿,但是目前没有浏览器完全支持它。
Ortiga

2
请参阅cs.tut.fi/~jkorpela/forms/file.html,“设置文件大小限制”,以了解为什么在客户端尝试这样做没有意义。
岩浆

您无权访问访客计算机上的本地文件系统,最好的办法是使apache限制文件大小,并在文件太大时停止上载。
布伦特·弗雷拉尔

在客户端执行此操作很愚蠢-除非您只是想为用户提供方便。“您必须验证服务器端。您可以验证客户端。”
d -_- b

2
有趣的...这似乎起作用:plupload.com。唯一的问题是,没有Flash,Silverlight,Gears等插件的IE8似乎默认为HTML4。
delphi

7

const input = document.getElementById('input')

input.addEventListener('change', (event) => {
  const target = event.target
  	if (target.files && target.files[0]) {

      /*Maximum allowed size in bytes
        5MB Example
        Change first operand(multiplier) for your needs*/
      const maxAllowedSize = 5 * 1024 * 1024;
      if (target.files[0].size > maxAllowedSize) {
      	// Here you can ask your users to load correct file
       	target.value = ''
      }
  }
})
<input type="file" id="input" />

如果您需要验证文件类型,请在下面的评论中写下,我将分享我的解决方案。

(扰流板:accept属性不是防弹解决方案)


2

视频文件示例(HTML + Javascript):

function upload_check()
{
    var upl = document.getElementById("file_id");
    var max = document.getElementById("max_id").value;

    if(upl.files[0].size > max)
    {
       alert("File too big!");
       upl.value = "";
    }
};
<form action="some_script" method="post" enctype="multipart/form-data">
    <input id="max_id" type="hidden" name="MAX_FILE_SIZE" value="250000000" />
    <input onchange="upload_check()" id="file_id" type="file" name="file_name" accept="video/*" />
    <input type="submit" value="Upload"/>
</form>


1

const input = document.getElementById('input')

input.addEventListener('change', (event) => {
  const target = event.target
  	if (target.files && target.files[0]) {

      /*Maximum allowed size in bytes
        5MB Example
        Change first operand(multiplier) for your needs*/
      const maxAllowedSize = 5 * 1024 * 1024;
      if (target.files[0].size > maxAllowedSize) {
      	// Here you can ask your users to load correct file
       	target.value = ''
      }
  }
})
<input type="file" id="input" />


-1
<script type="text/javascript">
    $(document).ready(function () {

        var uploadField = document.getElementById("file");

        uploadField.onchange = function () {
            if (this.files[0].size > 300000) {
                this.value = "";
                swal({
                    title: 'File is larger than 300 KB !!',
                    text: 'Please Select a file smaller than 300 KB',
                    type: 'error',
                    timer: 4000,
                    onOpen: () => {
                        swal.showLoading()
                        timerInterval = setInterval(() => {
                            swal.getContent().querySelector('strong')
                                .textContent = swal.getTimerLeft()
                        }, 100)
                    },
                    onClose: () => {
                        clearInterval(timerInterval)

                    }
                }).then((result) => {
                    if (
                        // Read more about handling dismissals
                        result.dismiss === swal.DismissReason.timer


                    ) {

                        console.log('I was closed by the timer')
                    }
                });

            };
        };



    });
</script>

1
请尝试在您的代码中添加一些说明。
Partho63 '19

仅使用JavaScript(客户端)代码是不可行的,因为可以轻松地绕开它。需要服务器端逻辑。
Akshay Anurag,
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.