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?

3 Answers 3

1

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>
Sign up to request clarification or add additional context in comments.

Comments

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 = '';
  }
}

Comments

0

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.