使用jquery / javascript进行文件上传验证

时间:2016-03-16 13:49:26

标签: javascript jquery angularjs

我只想上传图片。我的代码将检测它是否是图像,但我想禁用该按钮,直到文件选择正确,即图像。只有这样才能启用按钮。

是否使用AngularJs,javascipt或jQuery并不重要。

<SCRIPT type="text/javascript">
    function ValidateFileUpload() {
        var fuData = document.getElementById('fileChooser');
        var FileUploadPath = fuData.value;

        //To check if user upload any file
        if (FileUploadPath == '') {
            alert("Please upload an image");

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

            //The file uploaded is an image

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

                // To Display
                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]);
                }

            }

            //The file upload is NOT an image
            else {
                alert("Photo only allows file types of GIF, PNG, JPG, JPEG and BMP. ");

            }
        }
    }

<input type="file" name="dataFile" id="fileChooser" onchange="returnValidateFileUpload()" /><img src="images/noimg.jpg" id="blah"></br><input type="submit" value="submit" id="submit"  />

2 个答案:

答案 0 :(得分:0)

accept属性设置为"image/*"

<input type="file" accept="image/*" />

答案 1 :(得分:0)

<input type="file" accept="image/*">