4

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.

Midhun
  • 1,107
  • 10
  • 24

3 Answers3

5

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

Enno
  • 183
  • 2
  • 9
4

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" accepts="image/*" id="inp">

Important notes

  • accepts, 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.
Kaiido
  • 123,334
  • 13
  • 219
  • 285
0

You might consider a library (or copying its code) such as attr-accept to validate that the file dropped matches your accept="..." as close to the browser's native validation as possible.

For example: when you click on "Choose File" rather than dropping, it will validate based on accept="image/*,application/pdf").

KFunk
  • 2,956
  • 22
  • 33