Jay
Jay

Reputation: 539

How to limit the file type in HTML upload box?

I look around on the Net but cannot find the solution. But I just found that when we upload file to Flickr, the file dialog filter the file types automatically, how to make it??

Upvotes: 1

Views: 3013

Answers (2)

Piotr Rochala
Piotr Rochala

Reputation: 7781

You could parse .value property of this input and check for file extension using substr() method (i.e. if last 3 letters == 'png' etc.)

To perform more complex check you'd have to do it server-side.

Edit: This is a jQuery code that will do the job for you:

<script type="text/javascript">
    var Checker = {
        Extensions: ["jpg", "png", "gif", "bmp"],

        Validate: function(objid)
        {
            return jQuery.inArray(objid.value.substr(objid.value.length - 3, 3), Checker.Extensions) > -1;
        }
    };

    $(document).ready(function(){
        $('#submitButton').click(function(){
            if (Checker.Validate($('#selectFile')[0]))
            {
                alert("OK, we can submit!");
            } else {
                alert("This file type is not supported. \n Supported file types are: " 
                + Checker.Extensions.join(", "));
            }
        });
    });
</script>
<input type="file" id="selectFile" />
<input type="button" id="submitButton" value="Submit" />

Note: accept attribute does not work correctly on major browsers so javascript solution is best here, but please remember to check your file on server side again.

Upvotes: 1

pstanton
pstanton

Reputation: 36679

you can't get the .value property of a as mentioned in the other answer. it's restricted for security reasons.

there is also an 'accept' attribute which might be handy, eg:

<input type="file" name="picture" accept="image/gif, image/jpeg, image/jpg" />

i'm not sure how well supported it is among the various browsers though.

you can however create your own upload components using another technology such as java or flash.

Upvotes: 4

Related Questions