htmlformsform-fields

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.


Solution

  • 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