slolife
slolife

Reputation: 19870

How to determine if user selected a file for file upload?

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.

Upvotes: 71

Views: 121638

Answers (5)

sifr_dot_in
sifr_dot_in

Reputation: 3623

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

Upvotes: -1

Atiqur
Atiqur

Reputation: 81

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

Upvotes: 8

Elion Limanaj
Elion Limanaj

Reputation: 29

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.

Upvotes: 1

Ashu
Ashu

Reputation: 402

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 .

Upvotes: 5

Jason Bunting
Jason Bunting

Reputation: 58971

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

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

Upvotes: 133

Related Questions