Limit file format when using <input type=“file”>?

前端 未结 11 2461
盖世英雄少女心
盖世英雄少女心 2020-11-22 04:15

I\'d like to restrict the type of file that can be chosen from the native OS file chooser when the user clicks the Browse button in the

11条回答
  •  我寻月下人不归
    2020-11-22 04:55

    You can use the change event to monitor what the user selects and notify them at that point that the file is not acceptable. It does not limit the actual list of files displayed, but it is the closest you can do client-side, besides the poorly supported accept attribute.

    var file = document.getElementById('someId');
    
    file.onchange = function(e) {
      var ext = this.value.match(/\.([^\.]+)$/)[1];
      switch (ext) {
        case 'jpg':
        case 'bmp':
        case 'png':
        case 'tif':
          alert('Allowed');
          break;
        default:
          alert('Not allowed');
          this.value = '';
      }
    };

    JSFiddle

提交回复
热议问题