【问题标题】:How do I limit the number of file upload in html? [duplicate]如何限制html中文件上传的数量? [复制]
【发布时间】:2013-04-06 19:13:08
【问题描述】:

我想限制用户在输入标签中最多选择 6 个文件。目前,我的输入标签是这样的:

<input type="file" name="question_pic" id="id_question_pic" multiple/>

我想限制用户最多选择 6 个文件。我可以在服务器端返回错误,但我希望客户端先更改它。

有没有办法做到这一点?

谢谢。

【问题讨论】:

  • Pure html = "max-uploads = 1" or 2 or etc... 以为我会输入文件类型以防有人也在寻找它

标签: html


【解决方案1】:

你可以像这样使用 jQuery 函数:

$('.fileinput').change(function(){
    if(this.files.length>10)
        alert('Too many files')
});
// Prevent submission if limit is exceeded.
$('form').submit(function(){
    if(this.files.length>10)
        return false;
});

【讨论】:

  • 您可以通过清除文件列表值来阻止在更改功能中上传超过 10 个文件,如下所示:if(this.files.length&gt;10){ alert('to many files'); this.value = ''; } 不幸的是,您不能从文件列表对象中删除项目,您只能重置整个值。
  • 感谢您的意见,马克。它在 2020 年仍然正确吗?
  • @DrorBar 在此处了解 HTML5 文件 API 以限制所选文件的数量:dev.w3.org/2006/webapi/FileAPI
【解决方案2】:

您可以像这样使用 Jquery 或 Javascript:

<input type="file" name="question_pic" id="id_question_pic" max-uploads = 6/>

然后在 Jquery 中你可以这样做

Var number_of_uploads;
$("#id_question_pic").change(function() {
    if(number_of_uploads > $(this).attr(max-uploads))
    {
    alert('Your Message');
    }
    else
    {
    number_of_uploads = number_of_uploads + 1;
    }
});

您也可以在上传文件的表单提交中执行此操作。但如果您使用 Ajax 上传,我认为这很好。

【讨论】:

    猜你喜欢
    • 2013-08-05
    • 1970-01-01
    • 2012-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-08
    • 2012-09-21
    • 2010-12-06
    相关资源
    最近更新 更多