Is it possible to validate the size and type of input=file in html5

前端 未结 3 1249
一整个雨季
一整个雨季 2020-11-28 05:25

I was reading this http://dev.w3.org/html5/markup/input.file.html, but I only found the \"accept\" attribute.

I tried this



        
相关标签:
3条回答
  • 2020-11-28 05:36

    I could do this (demo):

    <!doctype html>
    <html>
    <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
    </head>
    <body>
        <form >
            <input type="file" id="f" data-max-size="32154" />
            <input type="submit" />
        </form>
    <script>
    $(function(){
        $('form').submit(function(){
            var isOk = true;
            $('input[type=file][data-max-size]').each(function(){
                if(typeof this.files[0] !== 'undefined'){
                    var maxSize = parseInt($(this).attr('max-size'),10),
                    size = this.files[0].size;
                    isOk = maxSize > size;
                    return isOk;
                }
            });
            return isOk;
        });
    });
    </script>
    </body>
    </html>
    
    0 讨论(0)
  • 2020-11-28 05:44

    if your using php for the backend maybe you can use this code.

    // Validate image file size
    if (($_FILES["file-input"]["size"] > 2000000)) {
        $msg = "Image File Size is Greater than 2MB.";
        header("Location: ../product.php?error=$msg");
        exit();
    }  
    
    0 讨论(0)
  • 2020-11-28 05:54
        <form  class="upload-form">
            <input class="upload-file" data-max-size="2048" type="file" >
            <input type=submit>
        </form>
        <script>
    $(function(){
        var fileInput = $('.upload-file');
        var maxSize = fileInput.data('max-size');
        $('.upload-form').submit(function(e){
            if(fileInput.get(0).files.length){
                var fileSize = fileInput.get(0).files[0].size; // in bytes
                if(fileSize>maxSize){
                    alert('file size is more then' + maxSize + ' bytes');
                    return false;
                }else{
                    alert('file size is correct- '+fileSize+' bytes');
                }
            }else{
                alert('choose file, please');
                return false;
            }
    
        });
    });
        </script>
    

    http://jsfiddle.net/9bhcB/2/

    0 讨论(0)
提交回复
热议问题