【问题标题】:send on post only files that are not empty仅发送非空文件
【发布时间】:2014-04-13 18:07:57
【问题描述】:

我在一个表单上有三个输入文件:

<td><input type="file" name="image_url1"/></td>
<td><input type="file" name="image_url2"/></td>
<td><input type="file" name="image_url3"/></td>

我只想发送(在发布时)我们选择的文件(输入文件保持为空 => 不发送)。

我该怎么做?

【问题讨论】:

  • 您必须手动发出请求并仅通过 Ajax 调用或其他一些技术传递您想要的项目。为什么不能在 Server 端手动处理空项?
  • 您仍然应该处理这个服务器端,而不是依赖客户端来确保文件不为空。

标签: javascript html file send


【解决方案1】:

您可以使用.length 检查文件长度,并禁用空控件。这样他们就不会被发布。

 $('input[type=file]').each(function () {
        if (this.value == "" || this.files.length == 0) {
            this.prop('disabled', true)
        }

    });

更新: 如果你不使用 jQuery,你可以通过简单的 javascript 来做到这一点:

var myFiles = document.querySelectorAll("input[type=file]");
for(var i = 0; i<myFiles.length; i++)
{
   if(myFiles[i].value == "" || myFiles[i].files.length == 0)
   {
      myFiles[i].disabled = true;
   }  
}

【讨论】:

    猜你喜欢
    • 2020-04-24
    • 2016-10-15
    • 2016-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-17
    • 2013-05-08
    相关资源
    最近更新 更多