HTML file input — “accept” attribute not working

亡梦爱人 提交于 2019-12-24 09:59:20

问题


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?


回答1:


<!DOCTYPE html>
<html>
<body>

Image:<input type="file" name="fileToUpload" id="fileToUpload" accept="image/*" id="capture"  required><br><br>
  Song:<input type="file" name="Audio" accept="audio/*"><br><br>

  <input type="submit">

</body>
</html>

image/* means it can accept all type of images you don't need to specify it try this. good luck




回答2:


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




回答3:


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>



回答4:


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


来源:https://stackoverflow.com/questions/45495047/html-file-input-accept-attribute-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!