【发布时间】:2011-08-12 14:49:06
【问题描述】:
HTML:
<input type="file" name="group_documents_file" id="group_documents_file" class="group-documents-file" />
规则:要上传的文件必须具有扩展名 JPEG、GIF 或 PNG,否则必须显示警报。
【问题讨论】:
标签: jquery html validation file-upload
HTML:
<input type="file" name="group_documents_file" id="group_documents_file" class="group-documents-file" />
规则:要上传的文件必须具有扩展名 JPEG、GIF 或 PNG,否则必须显示警报。
【问题讨论】:
标签: jquery html validation file-upload
你只需要拉取元素的值:
var fileName = $('#group_document_file').val();
var extension = fileName.slice('.')[fileName.slice('.').length - 1].toLowerCase();
if(extension == 'jpeg' || extension == 'gif' || extension == 'png')
// Show Validated Image
else
alert('Choose a supported image format');
【讨论】:
请参阅此处:get the filename of a fileupload in a document through javascript,了解如何获取文件名:
var extension = $('#group_documents_file').val().match(/[^.]+$/).pop().toLowerCase();
这应该会在文件名中的句点之后为您提供任何信息。
编辑:
如果你不想使用正则表达式,我建议使用 split, with pop:
var extension = $('#group_documents_file').val().split('.').pop().toLowerCase();
然后,要检查允许的扩展名,请执行以下操作:
if ( ~$.inArray(extension, ['jpg', 'jpeg', 'gif', 'png']) ) {
// correct file type...
} else {
// incorrect file type...
}
【讨论】:
以下获取文件的扩展名:
JS:
$('#group_documents_file').change(function(){
var value = this.value;
val = value.split("\\");
var file = (val[val.length - 1]).split('.');
var ext = file[file.length - 1];
alert(ext);
})
【讨论】:
试试这个
var fName = $('#group_document_file').val();
var validExtns ["jpg", "gif", "png"];
var extn = fName.slice('.')[fName.slice('.').length - 1];
if($.inArray(extn.toLowerCase(), validExtns) != -1){
// Show Validated Image
}
else{
alert('Invalid image format');
}
【讨论】: