【发布时间】:2015-08-26 11:18:41
【问题描述】:
这是我的文件输入元素:
<input type="file" id="StudentPhoto" value="StudentPhoto" style="display: none;">
这是验证函数:
$(document).ready(function() {
$('#StudentPhoto').change(function()
{
var file_data = $("#StudentPhoto").prop("files")[0];
var size = file_data.size;
var type = file_data.type;
var name = file_data.name;
var input = $("#StudentPhoto");
if(type !== 'image/png' && type !== 'image/jpg' && type !== 'image/jpeg')
{
alert("Only JPG & PNG files are allowed to upload as student photo.");
$('#StudentPhoto').click();
}
else if(size > 2097152)
{
alert("The maximum photo size is 2MB\n");
$('#StudentPhoto').click();
}
});
});
如果用户选择的文件的格式或大小无效,应该会弹出对话框让他重新选择文件,但没有,函数中的语句$('#StudentPhoto').click();没有工作。为什么?还有其他方法吗?
【问题讨论】:
-
它是一个文件输入,所以点击事件肯定是显示窗口并让用户选择文件
-
它也不起作用@ArunPJohny
-
对不起...我的意思是
doesn't...错过了 -
您应该在
<input type="file">中使用accept属性,而不是在JS 中签入。 -
不是真正的解决方法,但您可以通过设置
accept='.jpg | .jpeg | .png'属性来限制文件类型。当您提交表单而不是单击文件对话框的 open 按钮时,可能可以完成文件大小限制...
标签: javascript jquery