【问题标题】:How to determine if user selected a file for file upload?如何确定用户是否选择了文件进行文件上传?
【发布时间】:2010-09-07 22:55:25
【问题描述】:

如果我有一个

<input id="uploadFile" type="file" />

标签和提交按钮,我如何在 IE6(及更高版本)中确定用户是否选择了文件。

在 FF 中,我只是这样做:

var selected = document.getElementById("uploadBox").files.length > 0;

但这在 IE 中不起作用。

【问题讨论】:

标签: javascript html upload


【解决方案1】:

这适用于 IE(我相信还有 FF):

if(document.getElementById("uploadBox").value != "") {
   // you have a file
}

【讨论】:

  • 在 Chrome (75) 中不起作用,我获得了文件和文件夹的值
  • @Cid - 似乎按照我在这个答案中的描述工作,不确定你的问题是什么。您是否完全阅读了原始问题?你看我的回答了吗?
  • 我什至不记得一个月前我在寻找什么,我想我正在寻找一种方法来检查用户是否输入了文件或文件夹。我现在意识到这条评论超出了主题,我可能误读了这个问题
【解决方案2】:

这段代码在我的本地环境中工作,希望它也能在现场工作

var nme = document.getElementById("uploadFile");
if(nme.value.length < 4) {
    alert('Must Select any of your photo for upload!');
    nme.focus();
    return false;
}

【讨论】:

    【解决方案3】:
    function validateAndUpload(input){
        var URL = window.URL || window.webkitURL;
        var file = input.files[0];
    
        if (file) {
            var image = new Image();
    
            image.onload = function() {
                if (this.width) {
                     console.log('Image has width, I think it is real image');
                     //TODO: upload to backend
                }
            };
    
            image.src = URL.createObjectURL(file);
        }
    };​
    
    <input type="file" name="uploadPicture" accept="image/*" onChange="validateAndUpload(this);"/>
    

    在 change 时调用此函数。

    【讨论】:

      【解决方案4】:

      你可以使用:

          var files = uploadFile.files;
      
          if (files.length == 0) { console.log(true) } else { console.log(false) }
          if (files[0] == undefined) { console.log(true) } else { console.log(false) }
          if (files[0] == null) { console.log(true) } else { console.log(false) }
      

      所有三个都给出相同的结果。

      【讨论】:

        【解决方案5】:

        您可以使用 c# 在 asp.net 中检查它:

        html:

        <input id="FileID" runat="server" type="file"/>
        

        c#:

        if(FileID.PostedFile.FileName != "")
        {
            // do whatever you want if file is selected
        }
        else
        {
            //do whatever you want if no file is selected
        }
        

        【讨论】:

          猜你喜欢
          • 2016-11-12
          • 2016-06-06
          • 2011-02-26
          • 1970-01-01
          • 2016-02-15
          • 2018-04-01
          • 2021-11-02
          • 2010-10-10
          • 1970-01-01
          相关资源
          最近更新 更多