The previous article introduced cookie, Web Storage, and Web database technologies, and the next one will cover file Storage and offline applications.

File storage

Blob

  • concept

    Binary Large Object

  • API

    // constructor
    The blobParts parameter is an array of arrayBuffers, bloBs, etc. Options is an optional object that specifies the MIME type that is passed in and the way the line ends are written
    Blob(blobParts[,options])
      
    // File size, in unit B
    size
    
    // File MIME type, such as "image/jpeg"
    type
    
    // Intercepts the specified data at the specified start and end positions and returns a new Blob object
    slice(start[[,end],contentType])
    
    // Returns a Promise object, and the resolve result is an ArrayBuffer containing all the contents
    arrayBuffer()
    
    // Returns a Promise object, and the resolve result is a utF-8 string containing all the contents
    text()
    
    // Return a Promise object. The resolve result is a ReadableStream that can read everything
    stream()
    Copy the code

File

  • Relationship between File and Blob

    Blob is the base class of File, so what can be done with blobs can be done with files. Naturally, a File has all the attributes and methods of a Blob.

    file instanceof Blob; //true
    Copy the code
  • Common Acquisition methods

    1. Obtain the value from the FileList whose input type is File

    2. Obtain the DataTransfer returned from placing the dragged object to the specified position

    3. Constructor creation

  • attribute

    // Timestamp of the last modification of the file
    lastModified
    
    // The last time the file was modified Date object
    lastModifiedDate
    
    // The file name contains a suffix
    name
     
    // The relative path of the file relative to the directory selected by the user is not standard and is not recommended
    webkitRelativePath
    Copy the code

URL

  • concept

    Used to parse, construct, standardize, and encode urls. Easy to read or modify the URL content.

  • API

    Var url = new url ("http://user:[email protected]/main? data=123#abc"); As an example.
    
    // constructor
    // The url parameter can be an absolute url or a relative URL. If the relative URL is a relative URL, you need to specify the base parameter as the reference path.
    URL(url[,base])
    
    // Hash value, like # ABC
    hash
    
    // The host name is mudong.xyz
    host
    
    // Full link, as above http://user:[email protected]/main? data=123#abc
    href
    
    // The source is http://mudong.xyz
    origin
    
    // The password is mudong
    password
    
    // Path name, such as /main
    pathname
    
    // Port number, like ""
    port
    
    // Protocol name, such as "HTTP"
    protocol
    
    // Parameter string, as above "? data=123"
    search
    
    // The argument string object provides basic operations on the argument string:
    // append
    // delete
    // entries
    // forEach
    // get
    // getAll
    // has
    // keys
    // set
    // sort
    // toString
    // values
    Searchparams.get ('data') is 123
    searchParams
    
    // User name, such as name
    username
    
    // Return the entire URL
    toString()
    
    // Return the entire URL
    toJson()
    
    // Create a DOMString containing a unique blob link. The arguments can be File, Blob, or MediaSource
    / / sample:
    // URL.createObjectURL(new Blob([new ArrayBuffer(16)]))
    // "blob:chrome://new-tab-page/3ee0ed55-a791-4e07-80e9-186d9029fe64"
    URL.createObjectURL(obj)
    
    // Destroy the URL instance created earlier with url.createObjecturl. The argument is a BLOB link string
    / / sample:
    // URL.revokeObjectURL("blob:chrome://new-tab-page/3ee0ed55-a791-4e07-80e9-186d9029fe64")
    // undefined
    URL.revokeObjectURL(url)
    Copy the code
  • Blob ://URL, data://URL, file://URL

    Data ://URL encodes the content.

    Blob ://URL a simple reference to a bloB that the browser stores in memory or on disk.

    File: THE URL points to a file in the local system file, exposing only the file path, permission to browse the directory, and so on. Anything else can cause security problems.

  • The characteristics of

    Blob: urls have the same source as the script that created them and are only valid in documents of the same origin, whereas file: urls are non-cognate and are more flexible.

    Blob: THE URL is not permanent and is invalidated once the user closes or leaves the document that contains the script that created the BLOb URL.

    Blob: URLS are only allowed to be retrieved by GET requests, and once retrieved, the browser must return an HTTP 200 OK status code along with a Content-Type header using the BLOb Type attribute.

FileReader

  • concept

    Enable Web applications to asynchronously read file contents or binary buffer data stored locally on the computer.

  • API

    // File reading error exception
    error
    
    // Read status. The value can be 0 or 1, indicating that data is not loaded or is being loaded
    readyState
    
    // File contents
    result
    
    // Stop the read operation
    abort()
    
    // Start reading the data contents and return as an ArrayBuffer
    readAsArrayBuffer()
    
    // Start reading the data content and return it as a binary string
    readAsBinaryString()
    
    // Start reading the data content and return with dataURL
    readAsDataURL()
    
    // Start reading the data content and return it as plain text
    readAsText()
    
    // Listen stop read event
    onabort
    
    // Listen for read error events
    onerror
    
    // Listen for a successful read completion event
    onload
    
    // Listen for the read start event
    onloadstart
    
    // Listen for the read completion event, whether successful or not
    onloadend
    
    // Listen for read progress events
    onprogress
    
    Copy the code

Other file APIS

  • FileSystem/FileSystemSync

    Represents a file system. Access via window.requestfilesystem (). There are two attributes, one representing the name attribute of the file system name and the other representing the root attribute of the root directory of the file system

  • FileSystemEntry/FileSystemEntrySync

    Represents a single entity in a file system, either a file or a directory. In use drag and drop, through DataTransferItem webkitGetAsEntry (). The specific API is as follows:

    // Get the file system attached to the entity
    filesystem
    
    // Get the full absolute path from the root path to the entity
    fullPath
    
    // Whether the entity is a directory
    isDirectory
    
    // Whether the entity is a file
    isFile
    
    // Entity name
    name
    
    // Copy the entity to the specified location
    copyTo()
    
    // Get metadata about the file
    getMetadata()
    
    // Get the parent directory entity
    getParent()
    
    // Move the entity to the specified location, or rename the entity
    moveTo()
    
    // Delete the specified file or directory. The directory to be deleted must be empty
    remove()
    
    // Returns the url that identifies the entity, in the form filesystem:URL
    toURL()
    Copy the code
  • FileSystemFileEntry/FileSystemFileEntrySync

    Represents a file in a file system. API FileSystemEntry, only a unique method file, create a new readable file object and return

  • FileSystemDirectoryEntry/FileSystemDirectoryEntrySync

    Represents a directory in a file system. API with FileSystemEntry, unique methods as follows,

    / / create FileSystemDirectoryReader object, used to read directory of entities
    createReader()
    
    // Get the specified directory
    getDirectory()
    
    // Get the specified file in the directory
    getFile()
    Copy the code
  • FileSystemDirectoryReader/FileSystemDirectoryReaderSync

    Used to access all entities in a directory. There is only one method, readEntries, that returns an array of all entities in that directory.

Base64

  • concept

    An encoding format in which only six bits of data are stored in one byte; that is, data originally stored in three bytes is converted to base64 to be stored in four bytes.

    It is designed to store and transfer binary data over a medium that processes text data.

  • Relevant methods are provided

    Encoding base64:

    btoa(str)
    Copy the code

    Decoding base64:

    atob(base64Str)
    Copy the code
  • Unicode problem

    Because DOMString is a 16-bit encoded string, calling BTOA on Unicode strings in most browsers will cause a Character Out Of Range exception if a Character is outside the 8-bit ASCII encoded Character Range.

    Methods need to be enhanced to support UTF16. The following is an excerpt from one of the implementations of MDN.

    function btoaUTF16(str) {
    
      var u16Arr = new Uint16Array(str.length);
      Array.prototype.forEach.call(u16Arr, function(el, idx, arr) {
        arr[idx] = str.charCodeAt(idx);
      });
      return btoa(String.fromCharCode.apply(null.new Uint8Array(u16Arr.buffer)));
    
    }
    
    function atobUTF16(base64) {
    
      var binary = atob(base64);
      var u8Arr = new Uint8Array(binary.length);
      Array.prototype.forEach.call(u8Arr, function(el, idx, arr) {
        arr[idx] = binary.charCodeAt(idx);
      });
      return String.fromCharCode.apply(null.new Uint16Array(u8Arr.buffer));
    
    }
    
    Copy the code

Blob, Base64, ArrayBuffer conversion

  • The principle of

    The FileReader API is used to convert Blob to Base64 strings and ArrayBuffer.

    Using Typed Array to achieve base64 string, ArrayBuffer to Blob conversion.

  • Code implementation

  / / Blob base64
  function blobToB64(blob, cb) {

    var reader = new FileReader();
    reader.addEventListener('load'.function() {
      cb && cb(reader.result);
    });
    reader.readAsDataURL(blob, {
      type: blob.type
    });

  }

  / / Blob ArrayBuffer
  function blobToAb(blob, cb) {

    var reader = new FileReader();
    reader.addEventListener('load'.function() {
      cb && cb(reader.result);
    });
    reader.readAsArrayBuffer(blob);

  }

  / / ArrayBuffer base64
  function abToB64(arraybuffer, cb) {

    blobToB64(abToBlob(arraybuffer), cb);

  }

  / / ArrayBuffer Blob
  function abToBlob(arraybuffer, filename) {

    var u8arr = new Uint8Array(arraybuffer);
    if (filename) {
      return new File([u8arr], filename);
    } else {
      return new Blob([u8arr])
    }

  }

  / / base64 ArrayBuffer
  function b64ToAb(base64, cb) {

    blobToAb(b64ToBlob(base64), cb);

  }

  // Base64 format to Blob
  function b64ToBlob(base64, filename) {

    var arr = base64.split(', ');

    var mime = arr[0].match(/ : (. *?) ; /) [1];

    var binaryStr = atob(arr[1]);
    var i = binaryStr.length;
    var u8arr = new Uint8Array(i);
    while (i--) {
      u8arr[i] = binaryStr.charCodeAt(i);
    }

    if (filename) {
      return new File([u8arr], filename, {
        type: mime
      });
    } else {
      return new Blob([u8arr], {
        type: mime
      })
    }

  }
Copy the code

Offline Web Applications

Understand the offline

  • Access is still available on no network
  • Not cleared as the user clears the browser cache
  • Old data is overwritten by new data that was last accessed

Offline configuration

  • Configure the application cache manifest file

    The manifest file suffix is AppCache. When the server responds to the manifest file, the content type of the response header must be set to ‘text/cache-manifest’; otherwise, the application cannot be cached. The MANIFEST file format requires that the first line be a CACHE MANIFEST, followed by a list of resources to be cached, one resource per line. Comments begin with #. Here is an example,

    CACHE MANIFEST # List of resources to be cached CACHE: index.html index.css index.js images/logo.png # NETWORK field indicates that this URL resource is always obtained over the NETWORK. The URL supports * wildcard characters, indicating that any resource not in the list will be loaded by the browser over the NETWORK: list.html # FALLBACK field. Each line of the listing item contains two urls, the first is the URL prefix, and the second is the resource that needs to be loaded in the cache. FALLBACK: /articles 404.html will be used instead of accessing the resource specified by the second URL from the cache if the resource specified by the URL matching the prefix fails to load from the networkCopy the code
  • Specify a cache manifest file for HTML pages to be cached. In a single-page application, only one page should be cached, but in a multi-page application, there may be multiple pages

    <! DOCTYPEhtml>
    <html manifest="app.appcache">.</html>
    Copy the code

Question: How do I Uninstall an offline Web application? The server deletes the manifest file. 2. Delete the configuration of the manifest file from the cached HTML page

The cache update

  • Cache update mechanism

When online, the browser asynchronously checks the manifest file for updates. If so, the new manifest file and all resource files listed in the manifest are downloaded and saved back to the application cache.

Question: The resource file has changed, the manifest file has not, and the browser will only check if the manifest file has changed. What can I do to make resource files available for re-download? You can change the version number of the manifest file every time the manifest file changes. This ensures that the manifest file changes can be detected and all the resource files in the manifest can be downloaded again.

Question: Why is the updated resource accessed when it is not the updated resource? Browsing the checklist file and downloading the resource are asynchronous, meaning that the application may load the resource from the cache before the download is complete, so the updated resource is usually only seen on the second visit.

  • The cache object applicationCache

    Events:

    onchecking

    Triggered every time the HTML file that sets the manifest attribute is loaded

    onnoupdate

    Triggered when the application manifest file has not changed

    ondownloading

    The application manifest file has changed. Listen for the manifest file and the list of resources to cache to download

    onprogress

    Listen for the download progress of the application’s manifest file and the list of resources to cache

    oncached

    Triggered when uncached application download manifest files and resources end

    onupdateready

    Triggered when cached application download manifest files and resources end

    onerror

    Triggered when you are offline and cannot check the manifest file

    onobsolete

    Triggered when the application is online and cached, but the manifest file does not exist, and the application is removed from cache

    Properties:

    UNCACHED

    The application has no manifest attribute set and is not cached

    IDLE

    The manifest file is checked and the latest application is cached

    CHECKING

    The browser is checking the manifest file

    DOWNLOADING

    The browser is downloading and caching all the files listed in the listing

    UPDATEREADY

    The latest version of the application has been downloaded and cached

    OBSOLETE

    Manifest file does not exist, cache will be cleared

    Methods:

    update

    The update cache algorithm is explicitly called to check for the latest version of the application.

    swapCache

    Notify the browser to disallow the old cache, and all requests are fetched from the new cache. Calling this method only makes sense when the status attribute is UPDATEREADY or OBSOLETE; other status attributes are deprecated by direct throw exceptions.

other

Detection and monitoring of browser online status

  • Check whether the browser is online

    The navigator. Online properties

  • Listen for browser status changes

    Window. Onoffline events

    Window. Ononline events

Offline application data synchronization

  • In the offline state, the local data is saved by using localStorage. In the online state, the local data is synchronized to the server.

reference

  • The Definitive guide to JavaScript (6th edition)

  • Introduction to the ES6 Standard (Version 2)

  • Developer.mozilla.org/zh-CN/docs/…

  • Developer.mozilla.org/en-US/docs/…

  • Developer.mozilla.org/zh-CN/docs/…

  • Developer.mozilla.org/en-US/docs/…

  • Developer.mozilla.org/en-US/docs/…

  • Developer.mozilla.org/zh-CN/docs/…

  • Developer.mozilla.org/en-US/docs/…

At this point, the learning of storage and offline is over. Thanks for reading!!