Check selected file matches accept attribute on an <input> tag

后端 未结 3 1446
隐瞒了意图╮
隐瞒了意图╮ 2021-01-16 00:37

I wish to prevent the user from uploading a file the server will reject from a page with minimal JavaScript on it, ideally without adding any heavy dependencies like jQuery

3条回答
  •  半阙折子戏
    2021-01-16 01:20

    The accepted answer only works when accept is a single value. Also, it doesn't support the multiple attribute. For multiple accept values, comma separated, and multiple files, use the following:

    window.validateFileFormat = function() {
      const valid = [...i.files].every(file => {
        if (!i.accept) {
          return true;
        }
        return i.accept.replace(/\s/g, '').split(',').filter(accept => {
          return new RegExp(accept.replace('*', '.*')).test(file.type);
        }).length > 0;
      });
      alert('Valid: ' + valid);
    }
    

    Fiddle: http://jsfiddle.net/ynj8dsu6/

提交回复
热议问题