如何在上传前验证图片大小?

时间:2014-12-05 06:15:56

标签: javascript image validation

我想在上传图片之前验证图片大小和扩展名。我有图片扩展的代码,我想限制图片的大小。 以下是图片扩展的代码:

function ValidateFileUpload() {
    var fuData = document.getElementById('fileChooser');
    var FileUploadPath = fuData.value;


    if (FileUploadPath == '') {
        alert("Please upload an image");

    } else {
        var Extension = FileUploadPath.substring(
                FileUploadPath.lastIndexOf('.') + 1).toLowerCase();



 if (Extension == "gif" || Extension == "png" || Extension == "bmp"
                || Extension == "jpeg" || Extension == "jpg") {


            if (fuData.files && fuData.files[0]) {
                var reader = new FileReader();

                reader.onload = function(e) {
                    $('#blah').attr('src', e.target.result);
                }

                reader.readAsDataURL(fuData.files[0]);
            }

        } 


  else {
            alert("Photo only allows file types of GIF, PNG, JPG, JPEG and BMP. ");

        }
    }
}

HTML代码

<input type="file" name="image"  id="fileChooser" style="height:28px; width:175px;" onchange="return ValidateFileUpload()">

3 个答案:

答案 0 :(得分:5)

您可以将此代码与经过测试的HTML 5一起使用  演示:Demo for this

<input type="file" id="file" />

var _URL = window.URL || window.webkitURL;

$("#file").change(function(e) {

    var image, file;

    if ((file = this.files[0])) {

        image = new Image();

        image.onload = function() {

            alert("The image width is " +this.width + " and image height is " + this.height);
        };

        image.src = _URL.createObjectURL(file);


    }

});

答案 1 :(得分:1)

function ValidateFileUpload() {

var fuData = document.getElementById('fileChooser');
var FileUploadPath = fuData.value;


if (FileUploadPath == '') {
    alert("Please upload an image");

} else {
    var Extension = FileUploadPath.substring(FileUploadPath.lastIndexOf('.') + 1).toLowerCase();



    if (Extension == "gif" || Extension == "png" || Extension == "bmp"
                || Extension == "jpeg" || Extension == "jpg") {


            if (fuData.files && fuData.files[0]) {

                var size = fuData.files[0].size;

                if(size > MAX_SIZE){
                    alert("Maximum file size exceeds");
                    return;
                }else{
                    var reader = new FileReader();

                    reader.onload = function(e) {
                        $('#blah').attr('src', e.target.result);
                    }

                    reader.readAsDataURL(fuData.files[0]);
                }
            }

    } 


else {
        alert("Photo only allows file types of GIF, PNG, JPG, JPEG and BMP. ");
    }
}}

MAX_SIZE是您允许的最大文件大小。 你可以在我写的以下博客文章中找到一个很好的例子。

html5 file uploading example

答案 2 :(得分:0)

只需按照此示例http://jsbin.com/ulamor/213/edit?html,css,output

并在用户输入具有所需文件大小范围的文件时提交表单