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

后端 未结 3 1413
隐瞒了意图╮
隐瞒了意图╮ 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:24

    This one gathers the techniques from the other posts and make it to a short and easy function, working with multiple expressions:

    verifyAccept = function( file-type, accept ) {
        var type-regex = new RegExp( accept.replace( /\*/g, '.\*' ).replace( /\,/g, '|' ) );
        return type-regex.test( file-type );
    }
    

    instead of looping through the splitted accept string it uses regular expression features, just replace , through | which means the single expressions are or'ed.

提交回复
热议问题