简体   繁体   English

获取文件扩展名但无法获取文件名

[英]Get the extension of a file but can't get the filename

I am trying to check if a file has a valid extension or not. 我正在尝试检查文件是否具有有效的扩展名。 The problem is that when I give the file a random extension like .txt it doesn't get caught. 问题是当我给文件一个随机扩展名如.txt它不会被捕获。

I think the problem is that I am not actually getting the full filename. 我认为问题在于我实际上没有获得完整的文件名。

<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>

The PHP form: 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>

You could first obtain the file extension and then do what you need to with it: 您可以先获取文件扩展名,然后对它进行所需的处理:

var patt1 = /\.[0-9a-z]+$/i;
var fileName = "file.zip";
var theReturn = fileName.match(patt1);
alert(theReturn); //returns .zip

So, in your code, you would need to switch your switch statement to the following: 因此,在您的代码中,您需要将switch语句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
}

EDIT 编辑

Example to get file name and extension of uploaded file to FileUpload control: 将文件名和上载文件的扩展名获取到FileUpload控件的示例:

HTML 的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 的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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM