How to validate if there is any file to upload?

0

I have a form to upload files:

 @using (Html.BeginForm("importCSV", "Administrador", FormMethod.Post, new { @id = "upldFrm", @enctype = "multipart/form-data" }))
            {
                <div class="form-inline">

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

                    <input type="button" value="Enviar" id="enviarForm" />

                </div>

                <label style="color:red; white-space: pre-line">@ViewBag.Message</label>
            }

Before being sent, I would like to validate if the user even chose a file through JQuery.
What I have is this:

$("#enviarForm").click(function () {
                var file = $("#file");
                alert(file[0].size);
                if (file[0].size <= 0) {
                    alert("Selecione um arquivo!");
                } else {
                    $("#upldFrm").submit();
                }
            });

But in this case, size has always returned 20 even without choosing anything. Can anyone help me?

    
asked by anonymous 15.06.2015 / 13:49

1 answer

1

Using the files property of the <input/> of file this check can be done:

var input = document.querySelector('#file');
console.log(input.files.length);

Example usage:

document.querySelector('form').addEventListener('submit', function(e){
  e.preventDefault();
  if (this.querySelector('#file').files.length > 0) {
    alert('arquivo está selecionado');
  } else {
    alert('arquivo não está selecionado');
  }
}, false);
<form>
<input type="file" name="file" id="file"/>
<br/><input type="submit"/>
</form>
    
15.06.2015 / 14:08