如果我有一个

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

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

在FF中,我只是这样做:

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

但这在 IE 中不起作用。

有帮助吗?

解决方案

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

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

其他提示

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

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

在发生变化时调用此函数。

您可以使用:

    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) }

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top