使用 javascript 验证图像类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2036158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:30:24  来源:igfitidea点击:

Validate image type using javascript

javascript

提问by Selom

i have a form like this:

我有一个这样的表格:

<form method=post src=upload enctype="multipart/form-data">
    <input name="img1" id="img1" type="file">
    <input type="submit" value="Upload">
</form >

Please how can I valid this form using javascript so that only jpg files are uploaded. thanks for reading.

请问如何使用javascript验证此表单,以便仅上传jpg文件。谢谢阅读。

回答by CMS

You can bind the onsubmitevent of your form, and check if the valueof your file input ends with ".jpg" or ".jpeg", something like this:

您可以绑定onsubmit表单的事件,并检查value您的文件输入是否以“.jpg”或“.jpeg”结尾,如下所示:

window.onload = function () {
  var form = document.getElementById('uploadForm'),
      imageInput = document.getElementById('img1');

  form.onsubmit = function () {
    var isValid = /\.jpe?g$/i.test(imageInput.value);
    if (!isValid) {
      alert('Only jpg files allowed!');
    }

    return isValid;
  };
};

Check the above example here.

这里检查上面的例子。

回答by Mudaser Ali

Form :-

形式 :-

<form method=post src=upload enctype="multipart/form-data" onsubmit="return validateFile()">
<input name="img1" id="img1" type="file">
<input type="submit" value="Upload">
</form>

Javascript Code:-

Javascript代码:-

        function validateFile() 
        {
            var allowedExtension = ['jpeg', 'jpg'];
            var fileExtension = document.getElementById('img1').value.split('.').pop().toLowerCase();
            var isValidFile = false;

                for(var index in allowedExtension) {

                    if(fileExtension === allowedExtension[index]) {
                        isValidFile = true; 
                        break;
                    }
                }

                if(!isValidFile) {
                    alert('Allowed Extensions are : *.' + allowedExtension.join(', *.'));
                }

                return isValidFile;
        }

if you want to add more image extensions please add in allowedExtension array;

如果您想添加更多图像扩展名,请添加 allowedExtension 数组;

var allowedExtension = ['jpeg', 'jpg', 'png', 'gif', 'bmp'];

回答by mzarrugh

This is a simpler and more robust way to validate an image, and you don't have to think about all the possible image extensions out there.

这是一种更简单、更可靠的图像验证方法,您无需考虑所有可能的图像扩展名。

document.body.querySelector('input[type="file"]')
        .addEventListener('change', function () {
            if (this.files[0] && this.files[0].type.includes('image')) {
                console.log('file is an image');
            } else {
                console.log('file is not an image');
            }
        });

If you want strictly jpg

如果你想严格jpg

document.body.querySelector('input[type="file"]')
        .addEventListener('change', function () {
            if (this.files[0] && this.files[0].type === 'image/jpeg') {
                console.log('file is jpg');
            } else {
                console.log('file is not jpg');
            }
        });

回答by Darrell Brogdon

You can use the "accept" paramter to the input tag:

您可以将“接受”参数用于输入标签:

<input name="img1" id="img1" type="file" accept="image" />

Its not JavaScript but should still be helpful to prevent the user from even attempting to upload a non-image file.

它不是 JavaScript 但应该仍然有助于防止用户甚至尝试上传非图像文件。

回答by Dan F

71944has some javascript that looks like it might do what you need. Bear in mind that it's only client side validation, so you'll still want to validate it on the server too.

71944有一些 javascript,看起来它可以满足您的需求。请记住,这只是客户端验证,因此您仍然希望在服务器上验证它。

回答by pagboy

A Google search unearthed this: http://www.webdeveloper.com/forum/archive/index.php/t-104406.html

谷歌搜索发现了这一点:http: //www.webdeveloper.com/forum/archive/index.php/t-104406.html

For your application, I would recommend running the input through:

对于您的应用程序,我建议通过以下方式运行输入:

function valid(a){
    return a.indexOf(".jpg") != -1 && a.type == file;
}

That should work.

那应该工作。

回答by Mohini

<script>
var fileInput = document.getElementById("fileInput");
fileInput.addEventListener("change",function(event){
    document.getElementById("name").innerHTML = "NAME: " + event.target.files[0].name;
    document.getElementById("type").innerHTML = "TYPE: " + event.target.files[0].type;
    document.getElementById("size").innerHTML = "SIZE: " + event.target.files[0].size;
});
</script>
<input type="file" id="fileInput" name="file"/>