本地文件系统

首先要声明的是,这里的本地文件系统并不是客户端操作系统下的本地磁盘文件系统,而是Web应用程序在客户端创建和管理的一个与页面相关联的沙盒文件系统。

 

概述

本地文件系统(Local FileSystem)API是通过FileSystem对象和window.requestFileSystem()方法来实现的。

Web应用程序可以通过调用window.requestFileSystem()来请求对一个沙盒文件系统的访问权限。调用requestFileSystem()会创建一个新的沙盒存储空间。成功调用之后会返回一个FileSystem对象。

代码示例

请求文件系统

通过调用window.requestFileSystem()请求对沙盒文件系统的访问权限:

  //浏览器的兼容性
  window.requestFileSystem = window.requestFilsSystem || window.webkitRequestFileSystem;
  
  window.requestFileSystem(type, size, successCallback, opt_errorCallback);

下面对调用requestFileSystem()时传递的参数作个简单的介绍:

* type \\ 文件存储是否持久。可为PERSISTENT,TEMPORARY。通过TEMPORARY存储的数据可由浏览器自行决定删除。要请求PERSISTENT存储,必须获得用户或应用的明确授权,并需要用户向应用授予配额。
* size \\存储空间大小(以字节为单位)。
* successCallback \\ 文件系统请求成功时调用的回调函数。其参数为FileSystem对象。
* opt_errorCallback \\ 用于处理错误或获取文件系统的请求遭到拒绝时可选的回调。其参数为FileError对象。

创建文件夹

  fileSystem.root.getDirectory('Hudao', {create: true}, function(dirEntry) {
         console.log('The directory'name is '+ dirEntry.name);
         }, opt_errorCallback);

上面例子中,在根目录中创建一个文件夹。getDirectory()方法用来读和创建目录。该方法第一个参数可以传递一个名字或者路径来创建。

创建文件

  fileSystem.root.getFile('hudao.txt', {create: true, exclusive: true}, function(fileEntry) {
       console.log('The file's name is '+fileEntry.name);
  }, opt_errorCallback);

上面例子中在根目录下创建一个空的文件hudao.txt。getFile()方法用来读和创建文件。

拷贝文件

  function copy(currentDirec, srcEntry, destDir) {
    currentDirec.getFile(srcEntry, {}, function(fileEntry) {
      currentDirec.getDirectory(destDir, {}, function(dirEntry) {
        fileEntry.copyTo(dirEntry);
      }, errorHandler);
    }, errorHandler);
  }
  copy(fileSystem.root, 'hudao.txt', 'Documents/');

上面的例子拷贝hudao.txt从ROOT到Document目录下。

移动文件

  function move(currentDirec, srcEntry, directoyName) {
    currentDirec.getFile(srcEntry, {}, function(fileEntry) {
      currentDirec.getDirectory(directoryName, {}, function(dirEntry) {
        fileEntry.moveTo(dirEntry);
      }, errorHandler);
    }, errorHandler);
  }
  move(fileSystem.root, 'hudao.txt', 'Documents/');

上面的例子是移动hudao.txt到Document的目录下。

重命名文件

  function rename(currentDirec, srcEntry, newName) {
    currentDirec.getFile(srcEntry, {}, function(fileEntry) {
      fileEntry.moveTo(currentDirec, newName);
    }, errorHandler);
  }
  rename(fileSystem.root, 'hudao.txt', 'hudaokeji.txt');

上面的例子是将hudao.txt重命名成hudaokeji.txt。

参考

相关页面

外部链接