【问题标题】:Input file does not run function if empty输入文件为空时不运行函数
【发布时间】:2021-12-16 00:48:56
【问题描述】:

如果我插入png它可以工作,如果我插入jpg它可以工作,但是如果我将文件留空它就不起作用,为什么?该文件应该是 png 或空的。

function myFunction() {
  var fileTypecheck = document.getElementById("file").files[0].type.replace(/(.*)\//g, '');
  
  if(fileTypecheck == "png" || fileTypecheck.length == 0){
  
      alert("File is png or 0");
  }else{
      alert("File is NOT png or 0");
  }
}
<input type="file" name="file" id="file"  onchange="loadFile(event)" accept="image/png">

<button onclick="myFunction()">Click me</button>

【问题讨论】:

  • 提示:files[0]
  • “它不起作用”是什么意思?您收到错误消息吗?如果是这样,错误信息是什么?猜测一下,问题在于您试图访问files[0] 上的属性,而没有首先检查files 是否有长度。如果没有选择文件,那么files 将是一个空数组,因此files[0] 将是未定义的,这意味着添加.type 将引发错误。考虑使用optional chaining

标签: javascript function file input is-empty


【解决方案1】:

当没有文件时,files[0] 的索引不存在。您可以在files[0] 中添加一个问号 (Optional_chaining),这样它就不会在没有文件时崩溃。 然后你可以把fileTypecheck.length== 0改成!fileTypecheck,因为没有文件的时候是undefined。

function myFunction() {
  var fileTypecheck = document.getElementById("file").files[0]?.type.replace(/(.*)\//g, '');
  
  if(fileTypecheck == "png" || !fileTypecheck){
  
      alert("File is png or 0");
  }else{
      alert("File is NOT png or 0");
  }
}
<input type="file" name="file" id="file" accept="image/png">

<button onclick="myFunction()">Click me</button>

【讨论】:

    【解决方案2】:

    &lt;input type="file"/&gt; 没有选择文件时,其HTMLInputElement.files 属性为空,因此files[0]undefined

    顺便说一句,您不应该依赖浏览器始终准确地告诉您文件的类型:浏览器通常从其主机操作系统的文件扩展名到 MIME 类型填充 File.type 属性注册表不可靠且经常过时。

    也就是说,将您的代码更改为:请注意,我添加了防御性编程步骤来实际验证事物而不是做出假设:

    function myFunction() {
    
        const inp = document.getElementById("file");
        if( !inp || inp.type !== 'file' ) throw new Error( "'file' input element not found." );
        
        if( inp.files.length !== 1 ) {
            alert( "Please select a single file first." );
            return;
        }
    
        const file = inp.files[0];
        if( file.type === 'image/png' ) {
            // OK
        
        }
        else {
            alert( "Please select a PNG file." );
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-28
      • 2018-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-17
      • 1970-01-01
      • 2015-05-21
      相关资源
      最近更新 更多