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

4

在提交表单之前,有没有办法检查图片的大小?

我正在使用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个回答

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>

这个有效。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接