문제

I have a file upload in my page. I defined an attribute with name: "filetype".

<input filetype=".jpg|.jpeg|.png" id="attachments" type="file">

I want when I select a file from file upload, with the javascript, I check file type:

    function onSelect(e) {
    if (!e.files[0].extension.match('/' + $("input[type='file']").attr('filetype') + '/i')) {
        alert('file type is wrong');
        e.preventDefault();
    }    
}

Now, when I select a file with .jpg format, e.files[0].extension would be

.jpg

and '/' + $("input[type='file']").attr('filetype') + '/i' is

/.jpg|.jpeg|.png/i

but e.files[0].extension.match('/' + $("input[type='file']").attr('filetype') + '/i') returns

null

and then alert fires. Why? and how I solve this problem? Thanks.

도움이 되었습니까?

해결책

You can't build a literal regex with concatenation, you need to use the RegExp constructor.

I would suggest you do the following:

<input data-filetype="jpg|jpeg|png" id="attachments" type="file">

Then:

function onSelect(e) {
    // "this" is the file input
    // if you attach the function to an event
    // like `$('input:file').change(onSelect)`
    var filetypes = $(this).data('filetype');
    var re = RegExp('\\.('+ filetypes +')$','i');
    if (!re.test(e.files[0].extension)) {
        alert('file type is wrong');
        e.preventDefault();
    }    
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top