如何在上传前检查图像大小(例如1MB)

时间:2011-10-06 11:34:30

标签: jquery

在发送表单之前有没有办法检查图像大小?

我正在使用jquery.form

JS:

$(document).ready(function() {
    var options = {
        target:        '#myform',
    };
    $('#myformbutton').click(function() {
        $('#myform').ajaxSubmit(options);
        return false;
    });
});

HTML:

<form action="myaction" method="post" id="myform" enctype="multipart/form-data">
    <label for="id_title">Title</label>
    <input id="id_title" type="text" name="title" maxlength="255" />
    <label for="id_image">Image</label>
    <input type="file" name="image" id="id_image" />
    <input type="button" id="myformbutton" value="Add!" />
</form>

1 个答案:

答案 0 :(得分:12)

我回答我自己的问题:

    $(document).ready(function() {
        $('#id_image').bind('change', function() {
            if(this.files[0].size > 1000141){
                $('#formerror').html('File is too big');
                $('#myformbutton').hide();
            }else{
                $('#formerror').html(' ');
                $('#myformbutton').show('slow');
            }
        });
    });

和html:

        <div id="formerror"></div>
        <form action="myaction" method="post" id="myform" enctype="multipart/form-data">
             <label for="id_title">Title</label>
             <input id="id_title" type="text" name="title" maxlength="255" />
             <label for="id_image">Image</label>
             <input type="file" name="image" id="id_image" />
             <input type="button" id="myformbutton" value="Add!" />
        </form>

这很有效。