Reputation: 50268
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?
Upvotes: 2
Views: 10324
Reputation: 50268
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 = '';
}
}
Upvotes: 1
Reputation: 501
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>
Upvotes: 0
Reputation: 20095
The detail listing of browser support for "accept" attribute is listed in w3 schools. Have a look. It may help you.
Upvotes: 0