jQuery - INPUT type=File ,Image FileType 验证选项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4222502/
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
jQuery - INPUT type=File , Image FileType Validation options?
提问by AnApprentice
I have the following:
我有以下几点:
<input id="user_profile_pic" name="user[profile_pic]" type="file">
On the server I check to make sure it's an image, but I want to check on the clientside first.
在服务器上我检查以确保它是一个图像,但我想先在客户端检查。
How with jQuery can I alert the user if the file input file selected isn't a gif,jpg,png, or bmp?
如果选择的文件输入文件不是 gif、jpg、png 或 bmp,我如何使用 jQuery 提醒用户?
Thanks
谢谢
回答by Jess Telford
You want to check what the value of the element is, something along the lines of:
您想检查元素的值是什么,大致如下:
$("#user_profile_pic").change(function() {
var val = $(this).val();
switch(val.substring(val.lastIndexOf('.') + 1).toLowerCase()){
case 'gif': case 'jpg': case 'png':
alert("an image");
break;
default:
$(this).val('');
// error message here
alert("not an image");
break;
}
});
Edit
编辑
Code changed based on comment - now removes the value of the selected file if not an image.
根据注释更改的代码 - 如果不是图像,现在删除所选文件的值。
回答by Hardik Sondagar
It's pretty simple not needed any JavaScript validations . Just write this and it'll accept only image files.
非常简单,不需要任何 JavaScript 验证。只要写这个,它就会只接受图像文件。
<input type="file" multiple accept='image/*'>
回答by Alex
You could use a regular expression:
您可以使用正则表达式:
var val = $("#user_profile_pic").val();
if (!val.match(/(?:gif|jpg|png|bmp)$/)) {
// inputted file path is not an image of one of the above types
alert("inputted file path is not an image!");
}
Of course you could add more formats to the regular expression. There are more complex and comprehensive ways to accomplish this, but this method will accomplish the task as long as the image file path inputted ends in a standard image file extension.
当然,您可以向正则表达式添加更多格式。有更复杂和更全面的方法来实现这一点,但只要输入的图像文件路径以标准图像文件扩展名结尾,这种方法就可以完成任务。
回答by Dr.Molle
There may be browsers that allow you to create a <img/>
of the given path, by that you could check if it's a real image or not(if not the onerror-event should fire on the image and it will have a width/height of 0).
可能有浏览器允许您创建<img/>
给定路径的一个,这样您就可以检查它是否是真实图像(如果不是,则 onerror 事件应该在图像上触发并且它的宽度/高度为 0) .
But as this only works in some browsers and is an security-risk(in my mind) I would'nt suggest to do this, so my answer is: you can't validate there anything.
但由于这仅适用于某些浏览器并且存在安全风险(在我看来),因此我不建议这样做,所以我的答案是:您无法验证任何内容。
Checking the file-extensions like suggested by Alex may be an option, but the file-extension does not guarantee if it's a image. However, as a simple pre-check(not validation) it could be useful.
检查 Alex 建议的文件扩展名可能是一种选择,但文件扩展名并不能保证它是否是图像。但是,作为简单的预检查(不是验证),它可能很有用。
回答by vp_arth
How can we to check, that user selects image file?
我们如何检查,该用户选择了图像文件?
- By file extension validation
It's work as expected, text file with.png
extension pass here input[type=file][accept=image/*]
It initially hidesnon-image
files from user. But this filter works by extensions too. And user still can manually enter any existing file name.We can check mime type of result
dataUrl
, it starts withdata:mimetype;base64,...
. So, we needimage/*
mimetype.var file = $('#uploadfile'); file.on('change', function (e) { var reader = new FileReader(); reader.onload = function() { var data = reader.result; if (data.match(/^data:image\//)) { $('#thumbnail').attr('src', data); } else { console.error('Not an image'); } }; reader.readAsDataURL(file.prop('files')[0]); });
- 通过文件扩展名验证
它按预期工作,带有.png
扩展名的文本文件通过这里 input[type=file][accept=image/*]
它最初non-image
对用户隐藏文件。但是这个过滤器也适用于扩展。并且用户仍然可以手动输入任何现有的文件名。我们可以检查结果的 mime 类型
dataUrl
,它以data:mimetype;base64,...
. 所以,我们需要image/*
mimetype。var file = $('#uploadfile'); file.on('change', function (e) { var reader = new FileReader(); reader.onload = function() { var data = reader.result; if (data.match(/^data:image\//)) { $('#thumbnail').attr('src', data); } else { console.error('Not an image'); } }; reader.readAsDataURL(file.prop('files')[0]); });
回答by Bablu Ahmed
You can try like this
你可以这样试试
// Image upload validation
$(document).on('change', ':file',function () {
const file = this.files[0];
const fileType = file['type'];
const validImageTypes = ['image/jpeg', 'image/png'];
if (!validImageTypes.includes(fileType)) {
alert('Only JPEG and PNG file types are allowed');
this.value = '';
}
});