How to filter the file format by input type file?

Asked

Viewed 6,278 times

7

When it is sent I do a validation checking if the chosen file is the format I need so:

function validaExtensao(id) {
   var result = true;
   var extensoes = new Array('xls'); // Arquivos permitidos
   var ext = $('#' + id).val().split(".")[1].toLowerCase();
   if ($.inArray(ext, extensoes) === -1) { // Arquivo não permitido
      result = false; 
   }
   return result;
}

Now I would like to filter when and open the input file to show only the corresponding file types.

Example:

Normal: inserir a descrição da imagem aqui

Specified type: inserir a descrição da imagem aqui

Is it possible to do ? Cross-browser?

1 answer

11


Use the attribute accept.

Example accepting only files .xls:

<input type="file" name="meuInput" accept=".xls" />

The values of the attribute can be:

  • File extension (.xls, . jpg);
  • audio/* - all audio files;
  • video/* - all video files;
  • image/* - all image files;
  • media_type - media files. Media listing

More than one comma-separated attribute can be used, for example:

<input accept="audio/*,video/*,image/*" />

Note: according to the canIUse not all browsers support, for example IE9 and earlier, Edge, iOS Safari.

  • +1, was just that, just a detail add her support in browsers, in some like IE9,iOS 9.2 and Opera do not work: http://caniuse.com/#search=Accept

  • Perfect, added the note, thanks for the touch, ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.