繁体   English   中英

在提交表格之前,如何检查文件是否已选择上传

[英]How can I check if file has been chosen to upload before submitting form

我有一个可以上传文件的表格。

我提供了一个脚本,用于在提交表单之前检查文件大小是否过大,并且如果用户尝试上传大于2MB的文件,则会显示警告,并且如果文件小于2MB,则可以上传文件。 然后,我使用PHP验证表单并将其处理为电子邮件

但是,如果用户根本不尝试上传文件,则警告消息仍会弹出,从而阻止提交表单。

如果用户不想包含上传文件,如何允许提交表单? 我的代码是:

<script>
document.forms[0].addEventListener('submit', function( evt ) {
    var file = document.getElementById('file').files[0];

    if(file && file.size < 2097152) { // 2 MB (this size is in bytes)
          //Submit form        
    } else {
        //Prevent default and display error
        alert("File is  over 2Mb in size!");
        evt.preventDefault();
    }
}, false);
</script>

如果有人能帮助我找到答案,在此先感谢。

托格

如果用户不想包含上传文件,如何允许提交表单?

您需要更改if逻辑,以检查大小并仅在文件存在时停止表单提交 ,而并非总是如此。 现在,您的代码一直在检查文件,如果文件不存在,它将进入else块,从而停止提交事件。

我建议您按照以下方式重构逻辑。

<script>
 document.forms[0].addEventListener('submit', function( evt ) {
 var file = document.getElementById('file').files[0];

 if(file)  // perform the size check only if a file is present.
 {
   if(file.size < 2097152) { // 2 MB (this size is in bytes)
      //Submit form        
   } else {
     //Prevent default and display error
     alert("File is  over 2Mb in size!");
     evt.preventDefault();
   }
 }    

 }, false);
</script>

当没有文件上传时,此逻辑将提交表单;当有文件上传时,它将进行检查以确保文件小于2 MB。

如果未选择文件,则返回true

<script>
document.forms[0].addEventListener('submit', function( evt ) {
    var file = document.getElementById('file').files[0];

    if(!file)
        return true;

    if((file && file.size < 2097152)) { // 2 MB (this size is in bytes)
          //Submit form        
    } 
    else 
        //Prevent default and display error
        alert("File is  over 2Mb in size!");
        evt.preventDefault();
    }
}, false);
</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM