How to filter the format of the file by the input type file?

6

When it is sent I make a validation checking if the chosen file is of the format that I need:

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:

Typespecified:

Can it be done? Cross-browser?

    
asked by anonymous 06.01.2016 / 18:32

1 answer

8

Use the accept attribute.

Example accepting only .xls files:

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

Attribute values can be:

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

More than one attribute can be used, separated by commas, for example:

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

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

    
06.01.2016 / 18:36