javascript – Check if a file was selected "input file"

Question:

How do I check if a file has been selected?

<input type="file" id="id-input-file-2" name="arquivo" class="form-control arquivo" />

With the confirmation, I will start the upload automatically, without the need to click any button.

Answer:

you can use HTML5 validation

<form>
  <div>
    <input type="file" required />
  </div>
  <div>
    <input type="submit" value="enviar" />
  </div>
</form>

or simply check if the input has a value:

var fileUpload = document.getElementById("fileUpload");
var enviar = document.getElementById("enviar");
enviar.addEventListener("click", function (event) {
  if (fileUpload.files.length == 0) {
    alert("Nenhum Arquivo Selecionado");
    return;
  }

  if (fileUpload.files[0].type.indexOf("image") != 0) {
    alert("Este arquivo não é uma imagem");
    return;
  }
})
<form>
  <div>
    <input id="fileUpload" type="file" />
  </div>
  <div>
    <input id="enviar" type="button" value="enviar" />
  </div>
</form>

for your specific problem, you can use the input change event:

var arquivo = document.getElementById("arquivo");
var formulario = document.getElementById("formulario");

arquivo.addEventListener("change", function (event) {
  if (arquivo.files.length == 0) {
    alert("Nenhum Arquivo Selecionado");
    return;
  }

  //Enviando o Arquivo por AJAX e monitorando o Progresso.
  var data = new FormData(formulario);
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.open("POST", urlEnvio);
  xmlHttp.upload.onprogress = function(event) {
    if (event.lengthComputable) {
      var progresso = (event.loaded / event.total) * 100;
    }
  };
  xmlHttp.send(data);
})
<form id="formulario">
  <div>
    <input id="arquivo" type="file" />
  </div>
</form>

If you prefer, you can assemble the FormData on your nail, in this case the input will not need to belong to a form:

var data = new FormData();
data.append("arquivo", arquivo.files[0]);

As requested the same code in jQuery, I particularly don't see the need to use jQuery in this case.

var arquivo = $("#arquivo");

arquivo.on("change", function (event) {
  if (event.target.files.length == 0) {
    alert("Nenhum Arquivo Selecionado");
    return;
  }

  var data = new FormData();
  data.append("arquivo", event.target.files[0]);

  $.ajax({
    type: "POST",
    url: urlEnvio,
    data: data,
    success: function (response) { },
    dataType: dataType,
    processData: false,
    xhr: function() {
      var xmlHttp = $.ajaxSettings.xhr();
      xmlHttp.upload.onprogress = function(event) {
        if (event.lengthComputable) {
          var progresso = (event.loaded / event.total) * 100;
        }
      };
      return xmlHttp;
    }
  });
})
<form id="formulario">
  <div>
    <input id="arquivo" type="file" />
  </div>
</form>
Scroll to Top