可能重复:
How can the file extension be validated in an input type file using JQuery?
这是我的文件扩展验证码,以防止上传不需要的文件
有一个更简单的方法来编码吗?
任何人都可以改进吗?
<script>
function onSubmitForm(re) {
var formDOMObj = document.frmSend;
var file1 = formDOMObj.attach1.value;
var pdf=file1.toLowerCase().lastIndexOf(".pdf");
var doc=file1.toLowerCase().lastIndexOf(".doc");
var docx=file1.toLowerCase().lastIndexOf(".docx");
var xls=file1.toLowerCase().lastIndexOf(".xls");
var xlsx=file1.toLowerCase().lastIndexOf(".xlsx");
var wps=file1.toLowerCase().lastIndexOf(".wps");
if (file1 == "" )
{
alert("Please pick a file.")
return false;
}
else
if ( pdf == -1 && doc == -1 && docx == -1 && xls == -1 && xlsx == -1 && wps == -1 )
{
alert("File not acceped. Please upload your RESUME in .pdf, .doc, or docx")
frmSend.reset(re);
return false;
}
else
return true;
}
</script>
答案 0 :(得分:4)
简化:
var extension = file1.split('.').pop().toLowerCase();
var allowed = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'wps'];
if(allowed.indexOf(extension) === -1) {
// Not valid.
}
当然,文件不一定包含其扩展名所包含的内容。
答案 1 :(得分:2)
正则表达式很强大。
function onSubmitForm(re) {
var formDOMObj = document.frmSend;
var file1 = formDOMObj.attach1.value;
var acceptedTypes = ["pdf", "doc", "docx", "xls", "xlsx", "wps"];
var re = new RegExp("\\.(" + acceptedTypes.join("|") + ")$");
if (file1 == "" )
{
alert("Please pick a file.")
return false;
}
if (!re.test(file1))
{
alert("File not acceped. Please upload your RESUME in .pdf, .doc, or docx")
frmSend.reset(re);
return false;
}
return true;
}
答案 2 :(得分:1)
您不需要在代码中使用此代码
<input type="file" accept="application/pdf,application/msword">
答案 3 :(得分:0)
您也可以将扩展名分配给var和 在它上面做一个开关盒,这样你就可以处理不同的动作,如果你想要的话,那就是另一个可能更短的解决方案
function onSubmitForm(re) {
var formDOMObj = document.frmSend;
var file1 = formDOMObj.attach1.value;
var ext = file1.match(/\.(.+?)$/)
ext = ext == null ?"NONE": ext.ext[1].toLowerCase();
switch (ext) {
case "":
alert("Please pick a file.")
return false;
case "pdf":
case "doc":
case "docx":
case "xls":
case "xlsx":
case "wps":
return true;
default:
alert("File not acceped. Please upload your RESUME in .pdf, .doc, or docx")
frmSend.reset(re);
return false;
}
}
答案 4 :(得分:0)
我认为使用直接的RegExp更容易阅读:
function onSubmitForm(re) {
var formDOMObj = document.frmSend;
var file1 = formDOMObj.attach1.value;
if (file1 == "" )
{
alert("Please pick a file.")
return false;
}
if (!/\.(doc|docx|pdf|wps|xls|xlsx)$/.test(file1))
{
alert("File not acceped. Please upload your RESUME in .pdf, .doc, or docx")
frmSend.reset(re);
return false;
}
return true;
}