2

我使用 valums 文件上传器,但在上传之前我遇到了图像尺寸验证的问题。image_extensionimage_filesize返回false,但由于图片尺寸在onload async函数中,返回false无效,图片提交上传。

示例代码:

function create_uploader()
{
    var uploader = new qq.FileUploaderBasic(
    {
        button: $('#upload_button')[0],
        action: 'mdl/sys.upload.img.php',
        maxConnections: 7,
        debug: false,
        multiple: false,
        params:
        {
            upload_dir: '../files/_temp/',
            image_size: '1280,1024',
            thumb_size: '240,240'
        },
        onSubmit: function(id, fileName)
        {
            // validate extension
            var file_extension = (/[.]/.exec(fileName)) ? /[^.]+$/.exec(fileName):undefined;

            if (!(file_extension && /^(jpg|JPG|jpeg|JPEG|png|PNG)$/.test(file_extension)))
            {
                return false;
                // OK, execution stop
            }

            // validate image size
            var img_filesize = window.event.target.files[0].size;

            if (img_filesize > 1048576)
            {
                return false;
                // OK, execution stop
            }

            // validate image dimension
            var img_size = new Image();

            img_size.src = window.URL.createObjectURL(window.event.target.files[0]);

            img_size.onload = function()
            {
                var img_width = img_size.naturalWidth;
                var img_height = img_size.naturalHeight;

                window.URL.revokeObjectURL(img_size.src);

                if (img_width < 640 || img_width > 800)
                {
                    return false;
                }

                if (img_height < 480 || img_height > 600)
                {
                    return false;
                }
            }
        },
        onProgress: function(id, fileName, loaded, total)
        {
            // progress code
        },
        onComplete: function(id, fileName, results)
        {
            // complete code
        }
    });
}

create_uploader();

任何想法如何做到这一点?

编辑:子问题。我如何调用 onSubmit 过程取消和出列事件来评估文件上传器处理?如果这是可能的,那么我可以在我的验证中调用这个事件并取消上传图像..

4

1 回答 1

0

我有解决方案:) 这不完全是整个代码,因为它有点复杂。它对我来说是这样的:

系统上传文件

<script type="text/javascript">
    $(document).ready(function()
    {
        function create_uploader()
        {
            var internal_counter = 0; // very important for multiple upload!

            var uploader = new qq.FileUploaderBasic(
            {
                button: $('#upload_button')[0],
                action: 'mdl/sys.upload.img.php',
                maxConnections: 5,
                multiple: true,
                debug: false,
                params:
                {
                    upload_dir: '../files/_temp/',
                    image_size: '1280,1024',
                    thumb_size: '<?php echo isset ($thumb_size) ? $thumb_size : '240,240'; ?>'
                },
                onSubmit: function(id, fileName)
                {
                    // reset internal counter only if submit form button is enabled
                    if ($('#submit_form').prop('disabled') == false)
                    {
                        internal_counter = 0;
                    }

                    // find upload button and temperatory disable it
                    setTimeout(function(){$('#upload_button').css({'opacity': '0.25'}).find("input[type='file']").css({'cursor': 'default'}).prop('disabled', true)},25);

                    // disable submit form button
                    $('#submit_form').prop('disabled', true);

                    // create new form data
                    var image_data_temp = null;
                    var form_data = new FormData();

                    form_data.append('file', $("input[type='file']")[0].files[internal_counter]);
                    form_data.append('filesize', '5242880');
                    form_data.append('min_width', '600');
                    form_data.append('max_width', '4096');
                    form_data.append('min_height', '450');
                    form_data.append('max_height', '2160');

                    // send new form for validate
                    $.ajax(
                    {
                        type: 'POST',
                        url: 'mdl/sys.upload-validate.php',
                        async: false,
                        data: form_data,
                        cache: false,
                        contentType: false,
                        processData: false

                    }).done(function(results)
                    {
                        image_data_temp = results;
                    });

                    var image_data = image_data_temp.split(';');
                    /*
                    image_data[0] => status message
                    image_data[1] => name
                    image_data[2] => type
                    image_data[3] => size
                    image_data[4] => human size
                    image_data[5] => width
                    image_data[6] => height
                    image_data[7] => icon symbol shortcut
                    */

                    // counter must increase before check validation
                    internal_counter ++;

                    if (image_data[0] != 'ok')
                    {
                        // stop if validation is not OK
                        // you can here add some function for error etc.
                        console.log (image_data[0]);

                        // enable submit form button
                        $('#submit_form').prop('disabled', false);

                        // enable upload button
                        setTimeout(function(){$('#upload_button').css({'opacity': '1'}).find("input[type='file']").css({'cursor': 'pointer'}).prop('disabled', false);},25);

                        return false;
                    }

                    // validation is ok now, onProgress is processed

                },
                onProgress: function(id, fileName, loaded, total)
                {
                    // on progress code
                },
                onComplete: function(id, fileName, results)
                {
                    // process if is image uploaded
                    internal_counter = 0;

                    // enable submit form button
                    $('#submit_form').prop('disabled', false);

                    // enable upload button
                    $('#upload_button').css({'opacity': '1'}).find("input[type='file']").css({'cursor': 'pointer'}).prop('disabled', false);                    
                }
            });
        }

        create_uploader();

    });
</script>

sys.upload-validate.php

<?php
header ('Connection: close');

require_once '../sys.functions.php'; // it is not necessary

function show_data($str_a, $str_b, $str_c, $str_d, $str_e, $str_f, $str_g, $str_h)
{
    echo $str_a;
    echo ';';
    echo $str_b;
    echo ';';
    echo $str_c;
    echo ';';
    echo $str_d;
    echo ';';
    echo $str_e;
    echo ';';
    echo $str_f;
    echo ';';
    echo $str_g;
    echo ';';
    echo $str_h;
}

$image_info = getimagesize ($_FILES['file']['tmp_name']);

$image_width = $image_info[0];
$image_height = $image_info[1];

if
(
    $_FILES['file']['type'] != 'image/pjpeg' &&
    $_FILES['file']['type'] != 'image/jpeg' &&
    $_FILES['file']['type'] != 'image/x-png' &&
    $_FILES['file']['type'] != 'image/png'
)
{
    show_data
    (
        'Nesprávny typ súboru. Podporované sú iba JPG a PNG obrázky.',
        $_FILES['file']['name'],
        $_FILES['file']['type'],
        $_FILES['file']['size'],
        human_file_size($_FILES['file']['size']),
        $image_width,
        $image_height,
        'file'
    );

    return;
}

if ($_FILES['file']['size'] > (int)$_POST['filesize'])
{
    show_data
    (
        'Súbor je príliš veľký (' . human_file_size($_FILES['file']['size']) . '). Maximálna povolená veľkosť pre súbor je ' . human_file_size((int)$_POST['filesize']) . '.',
        $_FILES['file']['name'],
        $_FILES['file']['type'],
        $_FILES['file']['size'],
        human_file_size($_FILES['file']['size']),
        $image_width,
        $image_height,
        'file'
    );

    return;
}

if ($image_width < (int)$_POST['min_width'] || $image_width > (int)$_POST['max_width'])
{
    show_data
    (
        'Nesprávna šírka (' . $image_width . ' bodov). Minimálna šírka musí byť ' . $_POST['min_width'] . ', maximálna ' . $_POST['max_width'] . ' bodov.',
        $_FILES['file']['name'],
        $_FILES['file']['type'],
        $_FILES['file']['size'],
        human_file_size($_FILES['file']['size']),
        $image_width,
        $image_height,
        'wdt'
    );

    return;
}

if ($image_height < (int)$_POST['min_height'] || $image_height > (int)$_POST['max_height'])
{
    show_data
    (
        'Nesprávna výška (' . $image_height . ' bodov). Minimálna výška musí byť ' . $_POST['min_height'] . ', maximálna ' . $_POST['max_height'] . ' bodov.',
        $_FILES['file']['name'],
        $_FILES['file']['type'],
        $_FILES['file']['size'],
        human_file_size($_FILES['file']['size']),
        $image_width,
        $image_height,
        'hgh'
    );

    return;
}

show_data
(
    'ok',
    $_FILES['file']['name'],
    $_FILES['file']['type'],
    $_FILES['file']['size'],
    human_file_size($_FILES['file']['size']),
    $image_width,
    $image_height,
    null
);

return;
?>

也许它可以帮助某人:)

于 2016-04-22T23:28:25.443 回答