• Blob Blob Object represents an immutable, raw data-like file object. Blobs don’t necessarily represent data in JavaScript’s native format.FileInterface is based onBlob, inherits the functionality of bloB and extends it to support files on user systems.

    To construct a BLOb from other non-BLOb objects and data, use the blob () constructor. To create a subset bloB that contains another BLOB’s data, use the slice() method. To get the Blob object corresponding to the File on the user’s File system, see the File document.

  • FileList is an object that normally comes from an HTML input elementfilesProperty that allows you to access the file of the user’s choice
  • The File interface provides information about a File and allows JavaScript in a web page to access its content.
  • FileReader  FileReaderObject allows Web applications to asynchronously read the contents of files (or raw data buffers) stored on the user’s computer, usingFileBlobObject specifies the file or data to read.

    The File object can be a FileList object returned by the user after selecting a File on an element, or it can be generated by a drag-and-drop operation DataTransfer object, which can also be returned from mozGetAsFile() on an HTMLCanvasElement.

  • URL (not supported by Internet Explorer)

1. A Blob object

A Blob (Binary Large Object) Object represents a piece of Binary data. Other interfaces that manipulate binary data are built on top of this object.

Blob objects can be produced by using Blob constructors or slicing existing Blob objects into small pieces. Application scenarios include: breakpoint continuation of large files.

(1) The Blob constructor takes two arguments. The first argument is an array and the second argument is an object. Both parameters are optional.

let blob = new Blob(["Hello World"] and {"type" : "text\/xml" });
let a = document.createElement("a");
a.href = window.URL.createObjectURL(blob);
a.download = "hello-world.txt";
a.textContent = "Click on me to produce a hello-word.txt file.";
document.body.appendChild(a);Copy the code

(2) Slice method of Blob object, which is used to generate multiple new Blob objects.

document.querySelector('input[type="file"]').addEventListener('change', function(e) {
  let blob = this.files[0];  // The data obtained by this method is binary data

  const BYTES_PER_CHUNK = 1024 * 1024; // Define cutting unit 1M
  const TOTLE_SIZE = blob.size;  // Total file size

  let start = 0;
  let end = BYTES_PER_CHUNK;

  while(start < TOTLE_SIZE ) {   Blob. slice(start, end) is used as data to split the file and upload it to the server. Then the server merges the split binary data into a complete data
    // Note: in Ajax, xhr.responseType is set to blob, so the server receives binary data.
    // During the upload process, if the network is disconnected, the power is off, or the user refreshes the page, there may be some unsuccessful binary blocks. The next time you upload it
    // You can upload only parts of the resources that have not been uploaded successfully. This, of course, requires coordination on the server side. start = end;
    end = start + BYTES_PER_CHUNK;
  }
}, false);Copy the code

2. The FileList object

A FileList object targets the <input type=’file’ multiple /> tag. When the user selects a file using the <input type=’file’ multiple/> tag, the value of the files property of the tag is a FileList object. It is similar to an array in structure and contains multiple files selected by the user.

<input type="file" id="input" onchange="console.log(this.files)"Multiple /> // After selecting two files, the console can see two files in the FileList object, which are the binary data of the selected files.Copy the code



Figure 1-1 File print result

Today’s users are lazy and tend to drag and drop. You can also use drag and drop to get a FileList, so it’s easy for the user to upload a file.

let dropZone = document.getElementById('body');
dropZone.addEventListener('drop', handleFileSelect, false); // Prevent resources from opening as urls when a file is dragged into a web page. dropZone.ondragover =function () { return false; };
function handleFileSelect(evt) {
    evt.stopPropagation();
    evt.preventDefault();

    letfiles = evt.dataTransfer.files; // It contains the drag-and-drop files. console.log(files ) }Copy the code

3.File API

The File API provides the File object, which is a member of the FileList object. It contains some meta information about a File, such as the name of the File, the last time it was changed, the size of the File, and the File type. (as shown in figure 1-1)

4.FileReader API

The FileReader API is used to read files, that is, to read the contents of a file into memory. It takes a File object or a Blob object.

FileReader provides different ways to read files for different types of files.

  • readAsBinaryString(Blob|File): Returns a binary string containing an integer between 0 and 255 per byte. (This method is deprecated and readAsArrayBuffer() is officially recommended)
  • readAsText(Blob|File, opt_encoding): Returns a text string. By default, the text encoding format is’ UTF-8 ‘. You can specify other encoding formats through optional format parameters (you can obtain local. TXT,. Bat files, etc., read Word, Excell will garble).
  • readAsDataURL(Blob|File): returns a Base64 encoded data-URL object.
  • readAsArrayBuffer(Blob|File)Returns an ArrayBuffer object.

The FileReader object reads files asynchronously and can specify callbacks for a series of events.

  • Onabort method: Triggered when read abort or when the reader.abort() method is called.
  • Onerror method: triggered when reading error.
  • Onload method: triggered after successful reading.
  • Onloadend method: fired after reading, whether successful or not. The triggering sequence comes after onload or onError.
  • Onloadstart method: triggered when reading is about to start.
  • Onprogress method: triggered periodically during reading
Web page to obtain. TXT,. Bat text contentlet reader = new FileReader();
reader.onload = function(e) { //console.log(e.target.result); console.log(this.result); } reader.readAsText(blob);Copy the code

5. URL object

URL objects are used to generate urls to File objects or Blob objects.

letobjecturl = URL.createObjectURL(object); //object File object, Blob object, MediaSource object Img. SRC = objecturl //readFile objects are similar. Also can show picture on the web page / / the window. The URL. RevokeObjectURL (objecturl); // invalidate the URL objectCopy the code

The above code generates a URL for the binary data, something like “blob: HTTP %3A//test.com/2342e6730-f45c-47c1-8012-ccc706f17192”. This URL can be placed anywhere you would normally place a URL, such as the SRC attribute of the IMG tag. Note that every time the url.createObjecturl method is called, you get a different URL, even with the same binary data.

The existence time of this URL, equal to the existence time of the web page, once the page is refreshed or uninstalled, this URL is invalid. Alternatively, you can manually invalidate the URL by calling the url. revokeObjectURL method.

SAO Year, do you know how to achieve financial freedom? Scan the public account to take you on the road to financial freedom!



Reference:

www.w3.org/TR/FileAPI/

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

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

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

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

Javascript Standard Reference Tutorial (Alpha)

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

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