0

使用 Jscript 确定给定路径是文件夹还是文件的最简单方法是什么?

4

2 回答 2

2

你没有说你在什么环境下工作。如果您指的是Windows 脚本环境中的JScript,那么您可以使用该对象:Scripting.FileSystemObject

var fso = new ActiveXObject('Scripting.FileSystemObject');
if (fso.FileExists(path)) {
    WScript.Echo("It's a file!");
} else if (fso.FolderExists(path)) {
    WScript.Echo("It's a folder!");
} else {
    WScript.Echo("It's superman!");
}
于 2011-04-11T07:04:40.207 回答
0

仅使用 JavaScript 我知道你不能。但是,如果您知道文件的扩展名,则可以对文件进行一些验证。这里看一个例子。

JS

var pathX = "[?:[a-zA-Z0-9-_\.]+(?:.txt|.sql)"; /* File validation using extension*/

function testRegx(frm){
    var path = frm.testfile.value;

    if(path.toString().match(pathX)){
        alert("Valid");
    } else {
        alert("Invalid");
    }
}

HTML

<form name="testupload">
    <p>
    <input type="file" name="testfile">
    <input type="button" onClick="testRegx(this.form);" value="test">
    </p>
</form>

这种技术仍然不是最好的方法,因为您可以篡改文件以更改其扩展名,或者您可以通过在给定有效文件的基础上添加有效扩展名来重命名文件。

于 2011-04-11T06:43:03.563 回答