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

时间:2021-12-05 21:22:40

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, i.e. 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"  />

2 个解决方案

#1


0  

Use accept attribute set to "image/*"

使用接受属性设置为“image / *”

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

#2


0  

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

#1


0  

Use accept attribute set to "image/*"

使用接受属性设置为“image / *”

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

#2


0  

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

相关文章