Home > Web Front-end > H5 Tutorial > Detailed explanation of code cases of HTML5 file operation API

Detailed explanation of code cases of HTML5 file operation API

黄舟
Release: 2018-05-26 10:14:06
Original
4889 people have browsed it

Introduction

I often think that it would be very convenient if network applications could read and write files and directories. After moving from offline to online, applications have become more complex, and the lack of API in the file system has always hindered the progress of the network. Storing or interacting with binary data should not be limited to the desktop. What is gratifying is that due to the emergence of FileSystemAPI, this status quo has finally been changed. With FileSystemAPI, web applications can create, read, navigate, and write data to sandboxed portions of the user's local file system.

API is divided into the following different topics:

  • Reading and processing files: File/ Blob, FileList, FileReader

  • Create and write: BlobBuilder, FileWriter

  • ## Directory and file system access:

    DirectoryReader, FileEntry/DirectoryEntry, LocalFileSystem

Browser Support and Storage Limitations

At the time of writing this article, only the

GoogleChrome browser can implement this FileSystemAPI . There is currently no dedicated browser user interface for file / quota management. To store data on the user's system, your app may need to request quotas. However, you can use the --unlimited-quota-for-files flag to run the Chrome browser for testing. Additionally, if you are developing an app or extension for the Chrome Web Store, you can use unlimitedStoragemanifest file permissions without requesting quotas. Finally, the user receives a permission dialog box to grant, deny, or add storage to the app.

If you want to debug your application via

file://, you may need --allow-file-access-from-files mark. Failure to use these tags results in SECURITY_ERR or QUOTA_EXCEEDED_ERRFileError.

Request file system

Network applications can request access to the sandbox file system by calling window.requestFileSystem():

// Note: The file system has been prefixed as of Google Chrome 12:  
window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;  
  
window.requestFileSystem(type, size, successCallback, opt_errorCallback)
Copy after login

type

File Whether the storage should be durable. Possible values ​​include window.TEMPORARY and window.PERSISTENT. Data stored via TEMPORARY may be deleted at the browser's discretion (e.g. if more space is required). Clearing PERSISTENT storage requires explicit authorization from the user or app, and requires the user to grant a quota to your app. See Request Quotas.

size

The size in bytes that the application requires for storage.

successCallback

Callback called when the file system request is successful. Its parameter is a FileSystem object.

opt_errorCallback

An optional callback used to handle errors or when the request to obtain the file system is rejected. Its parameter is a FileError object.

If you call requestFileSystem() for the first time, the system will create new storage for your application. Note that this is a sandboxed file system, which means that one web app cannot access another app's files. This also means that you cannot read/write files in arbitrary folders on the user's hard drive (e.g. My Pictures, My Documents, etc.).

Usage example:

function onInitFs(fs) {
  console.log('Opened file system: ' + fs.name);}
  window.requestFileSystem(window.TEMPORARY, 5*1024*1024 /*5MB*/, onInitFs, errorHandler);
Copy after login

FileSystem The specification also defines the synchronization API (LocalFileSystemSync) interface planned for WebWorkers. However, this tutorial does not cover the synchronization API.

In the rest of this document, we will use the same handler to handle errors raised by asynchronous calls:

function errorHandler(e) {  
  var msg = '';  
  
  switch (e.code) {  
    case FileError.QUOTA_EXCEEDED_ERR:  
      msg = 'QUOTA_EXCEEDED_ERR';  
      break;  
    case FileError.NOT_FOUND_ERR:  
      msg = 'NOT_FOUND_ERR';  
      break;  
    case FileError.SECURITY_ERR:  
      msg = 'SECURITY_ERR';  
      break;  
    case FileError.INVALID_MODIFICATION_ERR:  
      msg = 'INVALID_MODIFICATION_ERR';  
      break;  
    case FileError.INVALID_STATE_ERR:  
      msg = 'INVALID_STATE_ERR';  
      break;  
    default:  
      msg = 'Unknown Error';  
      break;  
  };  
  
  console.log('Error: ' + msg);  
}
Copy after login

解的讯息。请求存储配额要使用 PERSISTENT 存储,您必须向用户取得存储持久数据的许可。由于浏览器可自行决定删除临时存储的数据,因此这一限制不适用于 TEMPORARY 存储。为了将 PERSISTENT 存储与 FileSystem API 配合使用,Chrome 浏览器使用基于 window.webkitStorageInfo 的新 API 以请求存储:

window.webkitStorageInfo.requestQuota(PERSISTENT, 1024*1024, function(grantedBytes) {  
  window.requestFileSystem(PERSISTENT, grantedBytes, onInitFs, errorHandler);  
}, function(e) {  
  console.log('Error', e);  
});
Copy after login

用户授予许可后,就不必再调用 requestQuota() 了。后续调用为无操作指令。您还可以使用 API 查询源的当前配额使用情况和分配情况:window.webkitStorageInfo.queryUsageAndQuota()使用文件沙盒环境中的文件通过 FileEntry 接口表示。FileEntry 包含标准文件系统中会有的属性类型(name、isFile...)和方法(remove、moveTo、copyTo...)。FileEntry 的属性和方法:

fileEntry.isFile === true  
fileEntry.isDirectory === false  
fileEntry.name  
fileEntry.fullPath  
...  
  
fileEntry.getMetadata(successCallback, opt_errorCallback);  
fileEntry.remove(successCallback, opt_errorCallback);  
fileEntry.moveTo(dirEntry, opt_newName, opt_successCallback, opt_errorCallback);  
fileEntry.copyTo(dirEntry, opt_newName, opt_successCallback, opt_errorCallback);  
fileEntry.getParent(successCallback, opt_errorCallback);  
fileEntry.toURL(opt_mimeType);  
  
fileEntry.file(successCallback, opt_errorCallback);  
fileEntry.createWriter(successCallback, opt_errorCallback);  
...
Copy after login

为了更好地理解 FileEntry,本部分还提供了执行常规任务的众多技巧。创建文件您可以使用文件系统的 getFile()(DirectoryEntry 接口的一种方法)查找或创建文件。请求文件系统后,系统会向成功回调传递FileSystem 对象,其中包含指向该应用相应文件系统的根的 DirectoryEntry (fs.root)。以下代码会在该应用相应文件系统的根中创建名为“log.txt”的空白文件:

function onInitFs(fs) {  
  
  fs.root.getFile('log.txt', {create: true, exclusive: true}, function(fileEntry) {  
  
    // fileEntry.isFile === true  
    // fileEntry.name == 'log.txt'  
    // fileEntry.fullPath == '/log.txt'  
  
  }, errorHandler);  
  
}  
  
window.requestFileSystem(window.TEMPORARY, 1024*1024, onInitFs, errorHandler);
Copy after login

请求文件系统后,系统会向成功处理程序传递 FileSystem 对象。我们可以将回调中的 fs.root.getFile() 命名为要创建的文件的文件名。您可以传递绝对路径或相对路径,但该路径必须有效。例如,如果您尝试创建一个其直接父级文件不存在的文件,将会导致出错。getFile() 的第二个参数是在文件不存在时从字面上说明函数行为的对象。在此示例中,create: true 会在文件不存在时创建文件,并在文件存在时 (exclusive: true) 引发错误。如果 create: false,系统只会获取并返回文件。无论是哪种情况,系统都不会覆盖文件内容,因为我们只是获取相关文件的引用路径。通过名称读取文件以下代码会检索名为“log.txt”的文件,并使用 FileReader API 读取文件内容,然后将其附加到页面上新的