java脚本中的图像宽度和高度验证 - Codeigniter

时间:2017-11-26 07:02:05

标签: javascript codeigniter

尝试从Javascript验证图像的上传文件高度和宽度。返回false并不起作用。

Javascript代码:

function Upload() {
    var fileUpload = document.getElementById("userfile");
    var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(.jpg|.png|.gif)$");
    if (regex.test(fileUpload.value.toLowerCase())) {
        if (typeof(fileUpload.files) != "undefined") {
            var reader = new FileReader();
            reader.readAsDataURL(fileUpload.files[0]);
            reader.onload = function(e) {
                var image = new Image();
                image.src = e.target.result;
                image.onload = function() {
                    var height = this.height;
                    var width = this.width;
                    if (height < 227 || width < 300) {
                        alert("Height and Width should be above 227px by 300px.");
                        return false;
                    }else{
                        alert("Uploaded image has valid Height and Width.");
                        return true;
                    }
                };
            }
        } else {
            alert("This browser does not support HTML5.");
            return false;
        }
    } else {
        alert("Please select a valid Image file.");
        return false;
    }
}  

HTML:

<form name="add_projects" id="add_projects"  method="post" enctype="multipart/form-data">
    <div class="row">
        <div class="col-md-4">
            <div class="form-group">
                <label>Project Name</label>
                <input type="text" name="project_name" id="project_name" class="form-control" value="<?php if(!empty($project)){ echo $project->project_name;}?>">
                <input type="hidden" name="id" id="id" value="<?php if(!empty($project)){ echo $project->id;}?>">
            </div>
        </div>
        <div class="col-md-4">
            <div class="form-group">
                <label>Project Sub Category Name</label>
                <input type="text" name="project_sub_name" id="project_sub_name" class="form-control" value="<?php if(!empty($project)){ echo $project->project_sub_name;}?>">
            </div>
        </div>
        <div class="col-md-4">
            <div class="form-group">
                <label>Tags</label>
                <input type="text" name="tags" id="tags" class="form-control" value="<?php if(!empty($project)){ echo $project->tags;}?>">
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <div class="form-group">
                <label>Poject Description</label>
                <textarea id="editor1" name="project_description" class="form-control" rows="10" cols="80"><?php if(!empty($project)){ echo $project->project_description;}?></textarea>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-6">
            <div class="form-group">
                <label>Current Image</label><br>
                <?php if(!empty($project) && $project->image !=""){?>
                    <img height="227" width="450" src="<?=base_url()?>assets/images/projects/<?=$project->image?>">
                <?php }else{ echo "No Image Selected";} ?>
            </div>
        </div>                      
        <div class="col-md-6">
            <div class="form-group">
                <label>New Image </label>
                <div id="preview" style="width:100%"></div>
            </div>  
        </div>
    </div>
    <div class="row">
        <div class="col-md-6">
            <div class="form-group">
                <label>Select Image </label>
                <input type="file" name="userfile" id="userfile">
                <input type="hidden" name="old_file" value="<?php if(!empty($project)){ echo $project->image;}?>">
                <input type="hidden" name="id" value="<?php if(!empty($project)){ echo $project->id;}?>">
                <span class="error">(Image should be more then 300px in width and 227px in height or above)</span>

            </div>
        </div>  
    </div>
    <div class="row">
        <div class="col-md-3">
            <div class="form-group">
                <input type="submit" onclick="return Upload();" name="submit" id="submit" value="Save Changes" class="btn btn-primary">
            </div>
        </div>
    </div>
</form>

即使图片的高度和宽度低于指定的像素,表单也会提交并且不会停止提交表单。

我在哪里弄错了?

我也在使用Jquery Validation作为表单(jquery.validate.min.js)。

1 个答案:

答案 0 :(得分:0)

您的代码存在很多问题。您尝试检查文件扩展名的方式无效。试图从嵌套函数内部返回将永远不会工作。您可以随意使用jQuery,但不要使用它。显然,尽可能使用vanilla javascript更好,但是你只是弄得一团糟。我把一些工作代码的一些例子放在一起,并试图尽可能地保持最小化。它检查文件大小,类型,因为你需要宽度和高度。

您可以注意到有两种验证正在进行中。一旦文件输入改变,一旦在表单上提交。这只是为了向您展示它可以完成。这个例子不一定完整,但应该让你去。我测试了它。按照发生的事情应该很容易。

<!doctype html>
<html lang="en-us">
    <head>
        <meta charset="utf-8">
        <title>Get Image Size</title>
    </head>
    <body>
        <form method="post" enctype="multipart/form-data" action="/whatever.php">
            <input id="file_input" type="file" name="userfile" />
            <input type="submit" name="submit" id="submit" value="Save Changes">
        </form>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script>
            (function($){
                // Local namespace
                var namespace = {

                    /* 
                     * Check file for type and size on submission.
                     * It is assumed that the file is previously determined to exist.
                     *
                     * @param  file element  like $(<file_input>).files[0]
                     * @param  int  like 2000000 for 2MB
                     * @param  string like "application/pdf|image/jpeg"
                     * @param  int like 227 for min pixel height 227
                     * @param  int like 300 for min pixel width 300
                     */
                    validate_file_upload: function( file, max_file_size, allowed_types, min_img_height, min_img_width ){
                        if( ! 'size' in file || ! 'type' in file )
                            return false;
                        if( file.size > max_file_size )
                            return false;
                        if( file.type != '' && allowed_types.indexOf( file.type ) == -1 )
                            return false;
                        var url = URL.createObjectURL( file );
                        var img = new Image;
                        var error = false;
                        img.onload = function(){
                            if( img.height < min_img_height || img.width < min_img_width ){
                                error = true;
                            }
                        };
                        img.src = url;
                        if( error )
                            return false;
                        return true;
                    },

                    /* 
                     * Instant validation of file input on field change.
                     * 
                     * @param  file element  like $(<file_input>).files[0]
                     * @param  int  like 2000000 for 2MB
                     * @param  string like "application/pdf|image/jpeg"
                     * @param  int like 40000000 for 40MB
                     * @param  int like 227 for min pixel height 227
                     * @param  int like 300 for min pixel width 300
                     */
                    validate_file_input_on_change: function( file, max_bytes, allowed_mimes, post_max_size, min_img_height, min_img_width ){
                        var error = false;
                        /* Is the file even a file? */
                        if( ! 'size' in file || ! 'type' in file )
                        {
                            error = true;
                            alert('File not able to be validated.');
                        }
                        /* Is filesize too large? */
                        else if(file.size > max_bytes){
                            error = true;
                            var readableSize = this._humanFileSize(file.size, true);
                            alert('File size of ~' + readableSize + ' too large to upload.');
                        }
                        /* Else filesize is not too large */
                        else{
                            /* Is mime type allowed? */
                            if( file.type != '' && allowed_mimes.indexOf(file.type) == -1 ){
                                error = true;
                                alert('Mime type ' + file.type + ' not uploadable.');
                            }
                            /* Else mime type was allowed */
                            else{
                                var fields_total = 0;
                                $('input[type="file"]').each(function(i,el){
                                    if( el.files[0] != undefined )
                                        fields_total += el.files[0].size;
                                });
                                /* Is total combined filesize meet server expectations */
                                if( fields_total > post_max_size ){
                                    error = true;
                                    var combinedTotal = this._humanFileSize(fields_total, true);
                                    var postMax = this._humanFileSize(post_max_size, true);
                                    alert('Combined filesize total of ' + combinedTotal + ' exceeds the server limitation of ' + postMax + '.\n\nPlease reduce the number of uploads.' );
                                }
                            }
                        }
                        /* Only check image dimensions if there is no existing error */
                        if( ! error ){
                            var url = URL.createObjectURL( file );
                            var img = new Image;
                            img.onload = function(){
                                if( img.height < min_img_height || img.width < min_img_width ){
                                    error = true;
                                    alert('Image height and/or width not large enough.');
                                }
                            };
                            img.src = url;
                        }
                        return ! error;
                    },

                    /* 
                     * Convert filesize in bytes to human readable MBs.
                     * Used by funcs.validate_file_input_on_change().
                     *
                     * @param  int  filesize in bytes, provided by File API
                     * @param  bool  is size vs size on disk
                     */
                    _humanFileSize: function(bytes, si) {
                        var thresh = si ? 1000 : 1024;
                        if( Math.abs(bytes) < thresh )
                            return bytes + ' B';
                        var units = si
                            ? ['kB','MB','GB','TB','PB','EB','ZB','YB']
                            : ['KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB'];
                        var u = -1;
                        do {
                            bytes /= thresh;
                            ++u;
                        } while( Math.abs(bytes) >= thresh && u < units.length - 1 );
                        return bytes.toFixed(1) + units[u];
                    }

                // End local namespace
                };

                window.funcs = ( window.funcs ) 
                    ? $.extend( window.funcs, namespace ) 
                    : namespace;

            })(this.jQuery);

            $(document).ready(function(){

                $('#file_input').on('change', function(){
                    var file = this.files[0];
                    // Check filesize and file type
                    var status = funcs.validate_file_input_on_change( 
                        file, 
                        // Max bytes
                        200000,
                        // Allowed mimes
                        'image/jpeg|image/png|image/gif', 
                        // Max post bytes
                        40000000, 
                        // Min height
                        227, 
                        // Min width
                        300 
                    );
                });

                $('#submit').on('click', function(e){
                    var file = $('#file_input')[0].files[0];
                    if( funcs.validate_file_upload(
                        file, 
                        // Max bytes
                        200000,
                        // Allowed mimes
                        'image/jpeg|image/png|image/gif', 
                        // Min height
                        227, 
                        // Min width
                        300
                    )){
                        return true;
                    }
                    e.preventDefault();
                    return false;
                });

            });
        </script>
    </body>
</html>