简体   繁体   English

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

[英]File upload validation using jquery/javascript

I want to upload images only. 我只想上传图像。 My code will detect whether it is an image or not but I want to disable the button until the file selection is correct, ie an image. 我的代码将检测它是否为图像,但是我想禁用该按钮,直到文件选择正确为止,即图像。 Only then should the button be enabled. 只有这样才能启用按钮。

Whether it uses AngularJs, javascipt or jQuery is not important. 它是否使用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"  />

使用accept属性设置为"image/*"

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM