2

After reading through the comments on this post, I came up with the following syntax for the accept attribute:

Images

<input type="file" accept="image/jpeg, image/png, image/gif, .jpeg, .png, .gif">

Audio

<input type="file" accept="audio/mpeg, audio/x-wav, .mp3, .wav">

This works perfectly on desktop browsers, but does not appear to filter files at all on iOS or Android.

Are there any cross-browser solutions available?

jabacchetta
  • 45,013
  • 9
  • 63
  • 75

3 Answers3

1

I was unable to get the accept attribute to work for mobile. Ultimately I had to add an onchange handler to the input (general idea shown below).

Keep in mind, you'll still want to use the accept attribute as shown in my question, because it will work on desktop.

const supportedExtensions = ['jpeg', 'jpg', 'png', 'gif'];

const handleChange = ({ target }) => {
  const path = target.value.split('.');
  const extension = `${path[path.length - 1]}`;

  if (supportedExtensions.includes(extension)) {
    // TODO: upload
  } else {
      // TODO: show "invalid file type" message to user

      // reset value
      target.value = '';
  }
}
jabacchetta
  • 45,013
  • 9
  • 63
  • 75
0

The detail listing of browser support for "accept" attribute is listed in w3 schools. Have a look. It may help you.

MKR
  • 19,739
  • 4
  • 23
  • 33
  • I tried just now on Android. The behavior is not exactly same but filter is working on Android for me. e.g. when I provided option `.doc` then only option to select `document` appeared. When I had only `image/*` then camera, drive etc. where provided but `document` option was not. – MKR Aug 04 '17 at 21:14
0

I got the same problem, found this page, here is my workaround using onChange event.

I know this isn't true filtering and this is pretty ugly (I don't it), but it works indeed. I tested on my iOS and Android devices.

<script type="text/javascript">
 let file;
 function checkFile() {
  file = document.querySelector('input[type=file]').files[0];
  if (file.type != "image/png") {
   file = null;
   document.getElementById('image').remove();
   let div = document.getElementById('div');
   let image = document.createElement('input');
   image.setAttribute('type', 'file');
   image.setAttribute('id', 'image');
   image.setAttribute('accept', 'image/png');
   image.setAttribute('onchange', 'checkFile()');
   div.appendChild(image);
   window.alert('unsupported file type');
  }
 }
</script>
<div id="div">
 <input type="file" id="image" accept="image/png" onchange="checkFile()">
</div>
yk125
  • 361
  • 3
  • 7