Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

FileHandle API

L'API FileHandle permet de manipuler des fichiers, y compris en les créant et en les modifiant (contrairement à l'API File). L'édition de fichiers utilise un système de verrou par tour pour éviter des situations de compétition

API

Créer une instance FileHandle

Afin de créer une instance FileHandle, il est nécessaire de disposer d'une base de données IndexedDB.

var idbreq = indexedDB.open("MaBaseDeDonnees");

idbreq.onsuccess = function(){
  var db = idbreq.result;
  var handleReq = db.mozCreateFileHandle("test.bin", "binary");
    
  handleReq.onsuccess = function(){
    var handle = handleReq.result;
    console.log('handle', handle);
  };
};

mozCreateFileHandle()reçoit deux arguments : un nom et un type, optionel. Ces deux arguments sont seulement descriptifs et ne sont pas utilisés par la base de données. Le nom peut être une chaîne de caractères vide et n'a pas à être unique. L'API ne porte aucune attention à la valeur de ces paramètres.

Le fragment de code ci-dessus crée un fichier temporaire qui n'existe qu'avec cette instance de FileHandle. Si vous souhaitez qu'un fichier subsiste après une actualisation de page ou un redémarrage d'applications, il faudra stocker le fichier de manière permanente, éventuellement au sein de la base de données.

var transaction = db.transaction(["test"], "readwrite");
var objectStore = transaction.objectStore("test");
objectStore.add(myFile, myKey).onsuccess = function(event) {
  // Le fichier est maintenant référencé en base de donnée.
}

L'interface FileHandle

interface FileHandle
{
  LockedFile open(optional DOMString mode);
  DOMRequest getFile()
  readonly attribute DOMString name;
  readonly attribute DOMString type;
  attribute Function? onabort;
  attribute Function? onerror;
};
open([mode="readonly"])
Returns a LockedFile. mode can be "readonly" or "readwrite"
getFile()
Returns a DOMRequest for a File. Upon success, you receive a read-only "snapshot" of file's content in the form of a File instance (that can be used anywhere a Blob is accepted, like FileReader, XMLHttpRequest, etc).
myFile.getFile().onsuccess = function(event) {
  var file = event.target.result;
  var transcation = myDatabase.transaction(["snapshots"], "readwrite");
  var objectStore = transaction.objectStore("snapshots");
  objectStore.add(file, snapshotKey).onsuccess = function(event) {
    // A new readonly copy of the file has been created.
  }
}
name
Nom de fichier
type
Réfère au type de contenuRefers to the content-type
abort event
Provoqué lorsque le fichier verrouillé a été interrompu
error event
Provoqué lorsqu'il y a une erreur interne quelconqueHappens when there is any sort of internal error

L'interface LockedFile

interface LockedFile
{
  readonly attribute FileHandle fileHandle;
  readonly attribute DOMString mode;
  readonly attribute boolean active;
  attribute any? location;
  FileRequest getMetadata(optional FileMetadataParameters parameters);
  FileRequest readAsArrayBuffer(unsigned long long size);
  FileRequest readAsText(unsigned long long size, optional DOMString encoding);
  FileRequest write(DOMString or ArrayBuffer or Blob value);
  FileRequest append(DOMString or ArrayBuffer or Blob value);
  FileRequest truncate(optional unsigned long long size);
  FileRequest flush();
  void abort();
  attribute Function? oncomplete;
  attribute Function? onabort;
  attribute Function? onerror;
};
fileHandle
FileHandle instance from which the lock was open
mode
"readonly" or "readwrite"
active
When created, the LockedFile is active. This LockedFile is the only object with write access to the actual underlying file. Operations on a LockedFile are performed in isolation, meaning that once a LockedFile is active, all operations of this LockedFile are guaranteed to happen sequentially on the underlying file without being interleaved with operations from other LockedFiles.
When the LockedFile becomes inactive, trying to perform read/write operations on the via using the same LockedFile will throw an error.
location
Offset in the file. This value is changed automatically after every read and every write. Reads and writes occur starting at the location. null means end-of-file
getMetadata(parameters)
Returns a FileRequest for metadata. The argument is an object with parameter names as object keys and booleans as value to retrieve the given properties asynchronously. No value means true. Currently, the possible parameters are size and lastModified.
readAsArrayBuffer(size)
Returns a FileRequest for an ArrayBuffer of the given size. The operation starts at the location. Moves location by the number of read bytes.
readAsText(size [, encoding])
Returns a FileRequest for a string of the given size with the provided encoding. The operation starts at the location. Moves location by the number of read bytes. Works the same way as the equivalent method in the FileReader API.
var lockedFile = myFile.open();
var request = lockedFile.readAsText(3);
request.onsuccess = function(event) {
  var text = request.result;
  // 3 characters have been read.
}
write(value)
Returns a FileRequest for the success or failure of the write operation. The write starts at the location and moves the location by the number of written bytes.
var lockedFile = myFile.open("readwrite");
var request = lockedFile.write("foo");
request.onsuccess = function(event) {
  // The string "foo" has been written.
}
append(value)
Returns a FileRequest for the success or failure of the append operation. The value is appended at the end of the file, regardless of the location. After the data is appended, location is set to null.
truncate([size])
Returns a FileRequest for the success or failure of the truncate operation.
If the method is called with a single argument, after a successful truncate, what remains on the file are the first size bytes regardless of the location.
If the method is called with no argument, what remains is the location first bytes.
flush()
This forces the buffered data to be transfered to disk. After a success notified by the returned FileRequest, you can be guaranteed that if the application crashes or is inadvertedly interrupted, the data is on disk.
abort()
Makes the LockedFile inactive and cancels all not already perfomed operations.
complete, abort, error events

FileRequest interface

An object of this type is returned by all asynchronous operations of the LockedFile interface. It inherits from DOMRequest and is similar to IDBRequest, with the addition of the onprogress event. Upon success, the, the result of the requested file operation is accessible from the result property.

interface FileRequest : DOMRequest
{
  readonly attribute LockedFile lockedFile;
  attribute Function? onprogress;
};
 

Description

Pourquoi une API différente de FileWriter?

The FileWriter specification defines FileWriters, objects aiming at representing editable files. Discussions on public-webapps led to the conclusion that the API would poorly behave in the case of different entities writing concurrently on the same file. The outcome of this discussion is the FileHandle API with its LockedFile and transaction mechanim.

Compatibilité des navigateurs

Fonctionnalité Chrome Firefox (Gecko) Internet Explorer Opera Safari
Support simple Pas de support 15 Pas de support Pas de support Pas de support
Fonctionnalité Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Support simple Pas de support 15 Pas de support Pas de support Pas de support

 

Étiquettes et contributeurs liés au document

 Contributeurs à cette page : SphinxKnight
 Dernière mise à jour par : SphinxKnight,