Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File field "accept" attribute not working properly when drag and drop file into it

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.

like image 440
Flames Avatar asked Oct 19 '25 13:10

Flames


2 Answers

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 snippet will work only if your user uploaded a single file. I don't know what you want to do in case they upload a folder or multiple files, but beware that they'll be able to do it, and thus that you will have to handle these cases.
like image 103
Kaiido Avatar answered Oct 22 '25 03:10

Kaiido


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

like image 29
Enno Avatar answered Oct 22 '25 04:10

Enno



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!