70

If I have a

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

tag, and a submit button, how do I determine, in IE6 (and above) if a file has been selected by the user.

In FF, I just do:

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

But that doesn't work in IE.

Raptor
  • 53,206
  • 45
  • 230
  • 366
slolife
  • 19,520
  • 20
  • 78
  • 121

5 Answers5

131

This works in IE (and FF, I believe):

if(document.getElementById("uploadBox").value != "") {
   // you have a file
}
Jason Bunting
  • 58,249
  • 14
  • 102
  • 93
  • 1
    @Cid - seems to work as-described by me in this answer, not sure what you're issue is. Did you completely read the original question? Did you read my answer? – Jason Bunting Sep 29 '19 at 21:37
  • 1
    I don't even remember what I was looking for a month ago, I suppose I was looking for a way to check if user inputed a file or a folder. I realize now that this comment was out of topic and I may have misread the question – Cid Sep 30 '19 at 06:48
8
var nme = document.getElementById("uploadFile");
if(nme.value.length < 4) {
    alert('Must Select any of your photo for upload!');
    nme.focus();
    return false;
}
lesolorzanov
  • 3,536
  • 8
  • 35
  • 53
Atiqur
  • 81
  • 1
  • 2
4
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);"/>

Call this function on change .

Ashu
  • 392
  • 1
  • 7
  • 16
1

You can use:

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

All three give the same result.

-1

The accepted answer is correct to check with "ID"

But, those who are here to check file with class-name,

here is the code:

var elements = document.getElementsByClassName('uploadFile_ClassName');
for (var i = 0; i < elements.length; ++i) {
    if(elements[i].value != "") {
        // file is selected here;
    }
}
sifr_dot_in
  • 3,153
  • 2
  • 33
  • 42