Jak określić, czy użytkownik wybrał plik do przesłania?

If I have a

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

Tag i przycisk submit, jak określić w IE6 (i wyżej), czy plik został wybrany przez użytkownika.

W FF po prostu robię:

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

Ale to nie działa w IE.

Author: Raptor, 2008-09-05

4 answers

To działa w IE (i FF, jak sądzę):

if(document.getElementById("uploadBox").value != "") {
   // you have a file
}
 90
Author: Jason Bunting,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-05 16:33:12

Ten fragment kodu działa w moim lokalnym środowisku, mam nadzieję, że będzie działał również w live

var nme = document.getElementById("uploadFile");
if(nme.value.length < 4) {
    alert('Must Select any of your photo for upload!');
    nme.focus();
    return false;
}
 5
Author: Atiqur,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-03 18:43:15
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);"/>

Wywołaj tę funkcję przy zmianie .

 0
Author: Ashu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-24 03:09:24

Możesz użyć:

    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) }
Wszystkie trzy dają ten sam wynik.
 0
Author: Elion Limanaj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-18 15:51:59