如何在上传前验证图片尺寸和尺寸?

时间:2014-05-15 13:11:31

标签: javascript

我想添加功能以在图片上传之前验证图片的大小。验证javascript存在以检查其他字段和文件类型,这似乎有效。我尝试插入一些代码来检查大小,但它不起作用。

HTML

 <input type="file" name="pin" id="pin" value="">

的javascript

function validateUpload()
{
description = $('textarea#blurb').val();
pin         = $('input#pin').val();
btitle      = $('input#btitle').val();
authname    = $('input#authname').val();


$('#error_description').html('');
$('#error_pin').html('');
$('#error_btitle').html('');
$('#error_authname').html('');

failed = 0 ;

if(description=="")
{
    $('#error_description').html('Please provide a description.');
    failed = 1;
}
if(btitle=="")
{
    $('#error_btitle').html('Please provide a title.');
    failed = 1;
}
if(authname=="")
{
    $('#error_authname').html('Please provide an author name.');
    failed = 1;
}
if(pin=="")
{
    $('#error_pin').html('Please upload a book cover.');
    failed = 1;
}
else{
    image = pin.toString().split(".");
    if((image[1]!='png')&&(image[1]!='jpg')&&(image[1]!='gif')&&(image[1]!='jpeg')&&(image[1]!='PNG')&&(image[1]!='GIF')&&(image[1]!='JPEG')&&(image[1]!='JPG'))
    {
        $('#error_pin').html('Invalid image.');
         failed = 1;
    }

}
$('#pin').bind('change', function() {
            if(this.files[0].size > 200000){
                $('#error_pin').html('File is too large.');
                failed = 1;
            }
        });





if(failed==1)
{
    return false;
}
else{
    return true;
}

1 个答案:

答案 0 :(得分:0)

你可以改变这个&#39; to:$(&#39; #pin&#39;)[0]并尝试

改变这个:

 if(this.files[0].size > 200000){
            $('#error_pin').html('File is too large.');
            failed = 1;
 }

进入

if($('#pin')[0].files[0].size > 200000){
            $('#error_pin').html('File is too large.');
            failed = 1;
 }