65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 Javascript 进行客户端文件处理

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.25/5 (13投票s)

2007年5月21日

CPOL

2分钟阅读

viewsIcon

191042

使用 Javascript 在客户端进行文件处理。

引言

Javascript 拥有丰富的属性和方法来创建、操作和管理驱动器、文件和文件夹。 您可以使用 Javascript,就像使用任何其他现代编程语言一样。 例如,您可以使用它来打开文件、写入文件、从中读取等。

Using the Code

Javascript 中的文件处理可以使用 FileSystemObject 对象及其属性和方法来完成。 此对象是 Microsoft 脚本引擎的一部分,因此仅适用于 Microsoft Windows 操作系统。

以下代码片段在指定位置创建一个新文件,并将“File handling in JavaScript”写入其中。

var fso = new ActiveXObject("Scripting.FileSystemObject");
// 2=overwrite, true=create if not exist, 0 = ASCII
varFileObject = fso.OpenTextFile("C:\\Sachin.txt", 2, true,0);
varFileObject.write("File handling in Javascript");
varFileObject.close();

函数 OpenTextFile 的参数如下

参数 1:PATH - 文件将在客户端机器上指定的路径中创建。 如果此处仅提及文件名,则文件将保存在客户端系统的桌面上。

参数 2:I/O 模式,指示文件打开的模式。 可能的值是

  • 1:以只读方式打开文件。
  • 2:以写入方式打开文件。
  • 8:以追加方式打开文件。

参数 3:CREATE 是一个布尔值,指示如果文件不存在是否创建文件(true),或者如果文件不存在是否发出错误消息(false)。

参数 4:FORMAT 是可选的,指示文件类型。 如果未指定,则默认文件类型为 ASCII。 格式的可能值是

  • TristateUseDefault - 2:使用系统默认值打开文件
  • TristateTrue -1:以 Unicode 方式打开文件
  • TristateFalse 0:以 ASCII 方式打开文件

以下是 FileSystemObject 提供的用于文件处理的一些方法

MoveFile(source, destination)
MoveFolder(source, destination)
CopyFile(source, destination, overwriteFlag) //overwriteFlag= true/false
CopyFolder(source, destination, overwriteFlag) //overwriteFlag= true/false
CreateFolder(folderName)
CreateTextFile(fileName, overwriteFlag)//overwriteFlag= true/false
DeleteFile(fileName, readPermissionFlag)//readPermissionFlag= true/false
DeleteFolder(folderName, readPermissionFlag)//readPermissionFlag= true/false
DriveExists(letterDrive)
FileExists(fileName)
FolderExists(folderName)
GetSpecialFolder(folderCode) /* The given folderCode is either 0 for a 
windows folder, 1 for a system folder, or 2 for a temporary folder. 
A full path is returned. On a typical installation, "c:\windows" 
is returned as the windows folder, "c:\windows\system" is returned 
as the system folder, and "c:\windows\temp" is returned as the temporary folder. */

关注点

在实现 FileSystemObject 之前,需要注意几点。 由于它是一个 ActiveX 对象,因此如果客户端机器上的安全级别较高,则不会创建它。 因此,必须将网站添加到受信任的站点列表中,以便可以创建 ActiveX 对象。

在创建文件时,用户必须在指定的路径中具有写入权限。 在存在不确定性的情况下,最好将文件写入系统的临时文件夹。 可以使用以下方法找到 Temp 文件夹的路径

GetSpecialFolder(2)

上述主题仅适用于 IE。 下面的链接提供了一个关于如何在 Mozilla 中实现文件操作的想法。 以下代码可用于检查浏览器类型

if (navigator.userAgent.indexOf("Opera") >= 0)
{
    alert("This example doesn't work in Opera") ; 
    return ;
}
if (navigator.userAgent.indexOf("MSIE") >= 0)
{ 
    alert("This example works in IE") ; 
    return ;
} 
if (navigator.userAgent.indexOf("Mozilla") >= 0)
{
    alert("This example doesn't work in Mozilla") ; 
    alert("Check the following link: <a href="http://www.mozilla.org/js/js-file" + 
          "-object.html" title="http://www.mozilla.org/js/js-file-object" + 
          ".html">http://www.mozilla.org/js/js-file-object.html</a>") ;
    return ;
}

//
© . All rights reserved.