我正在尝试检查文件是否具有有效的扩展名。问题是当我给文件一个随机扩展名.txt
时,它不会被抓住。
我认为问题在于我实际上并没有获得完整的文件名。
<script type="text/javascript">
function getExtension(fileName)
{
var parts = fileName.split('.');
return parts[parts.length - 1];
}
function isVideo(fileName)
{
var ext = getExtension(fileName);
switch (ext.toLowerCase())
{
case 'mp4': return true;
}
return false;
}
function check()
{
var f = document.getElementsByID('file');
if(isVideo(f.value) && document.getElementById('file').value)
{
return true;
}
document.getElementById('errMsg').style.display = '';
return false;
}
</script>
PHP表格:
<?php
$nexturl = "http://localhost/index.php";
?>
<form action="<?php echo($response->url); ?>?nexturl=<?php echo(urlencode($nexturl)); ?>" method="post" enctype="multipart/form-data" onsubmit="return check();">
<input id="file" type="file" name="file"/>
<div id="errMsg" style="display:none;color:red">
Bad file type.
</div>
<input type="hidden" name="token" value="<?php echo($response->token); ?>"/>
<input type="submit" value="go" />
</form>
</php>
答案 0 :(得分:0)
您可以先获取文件扩展名,然后使用它执行所需操作:
var patt1 = /\.[0-9a-z]+$/i;
var fileName = "file.zip";
var theReturn = fileName.match(patt1);
alert(theReturn); //returns .zip
因此,在您的代码中,您需要将switch
语句切换为以下内容:
function isVideo(fileName)
{
var patt1 = /\.[0-9a-z]+$/i;
var fileName = "file.zip";
var theReturn = fileName.match(patt1);
switch (theReturn.toLowerCase())
{
case '.mp4': return true; //make sure it's .mp4 instead of just mp4
}
retrun false
}
修改强>
获取文件名和上传文件扩展名到FileUpload控件的示例:
<强> HTML 强>
<!DOCTYPE Html />
<html>
<head>
<title></title>
</head>
<body>
<input id="File1" type="file" />
<input type="button" id="btnGetExt" value="Get File Extension"/>
<script type="text/javascript" src="theJS.js"></script>
</body>
</html>
<强>的JavaScript 强>
btnGetExt.onclick = function () {
var patt1 = /\.[0-9a-z]+$/i;
var fileName = document.getElementById('File1').value;
alert(fileName);
var theReturn = fileName.match(patt1);
alert(theReturn);
}