I have file field like this:
<input type="file" name="pic" accept="image/*">
it works correctly when i click and choose file but it accept all type of files when i drag and drop files into it.
Any idea ?
FYI : i have fixed this issue by adding a server side validation.
The accept parameter is used to let the browser know it should ask the OS for a file selector dialog which would accept only these type of files.
So this is actually an OS feature.
Now, when you drag&drop a file, the browser doesn't require to open a file selector dialog, so this attribute is not used.
But you can still listen to the change event and do your checking there.
inp.onchange = function(e){
e.preventDefault();
var file = this.files[0];
if(file.type.indexOf('image/') !== 0) {
this.value = null;
console.log("invalid");
}
else {
console.log('valid file');
}
}
Drop a file on this input. <br>
<input type="file" accept="image/*" id="inp">
Important notes
accept
, just like MIME Type checking is only done against the file extension, i.e really easily spoofable, you can try a magic-number check, but you should anyway always check from the server.The above answer does not really answer the question, it does not use the accept value, it just validates images. If the accept value would be something like 'text/plain' it will fail.
you can use this verify function to validate the file-type on the accept string:
verifyAccept = function( file-type, accept ) {
var type-regex = new RegExp( accept.replace( /\*/g, '.\*' ).replace( /\,/g, '|' ) );
return type-regex.test( file-type );
}
mentioned here: Check selected file matches accept attribute on an <input> tag
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With