File object, FileList object, FileReader object

File Object

The File object represents a file and is used to read and write file information. It inherits the Blob object, or a special kind of Blob object, it can be used in all occasions where the Blob object can be used.

The most common use case is the file upload control of the form (<input type="file">). After the user selects the file, the browser will generate an array, which contains the files selected by each user, and they are all File Instance object.

// HTML code is as follows
// <input id="fileItem" type="file">
var file = document.getElementById("fileItem").files[0];
file instanceof File; // true

In the above code, file is the first file selected by the user, and it is an instance of File.

Constructor

The browser natively provides a File() constructor to generate File instance objects.

new File(array, name [, options])

The File() constructor accepts three parameters.

-Array: An array whose members can be binary objects or strings, representing the contents of the file. -name: string, which means file name or file path. -options: configure the object, set the properties of the instance. This parameter is optional.

The third parameter configuration object, you can set two properties.

-type: string, representing the MIME type of the instance object, the default value is an empty string. -lastModified: timestamp, indicating the time of last modification, the default is Date.now().

Below is an example.

var file = new File(["foo"], "foo.txt", {
  type: "text/plain",
});

Instance attributes and instance methods

The File object has the following instance properties.

-File.lastModified: Last modified time -File.name: file name or file path -File.size: file size (in bytes) -File.type: the MIME type of the file

var myFile = new File([], "file.bin", {
  lastModified: new Date(2018, 1, 1),
});
myFile.lastModified; // 1517414400000
myFile.name; // "file.bin"
myFile.size; // 0
myFile.type; // ""

In the above code, since the content of myFile is empty and the MIME type is not set, the size attribute is equal to 0 and the type attribute is equal to an empty string.

The File object does not have its own instance method. Since it inherits the Blob object, the Blob instance method slice() can be used.

FileList object

The FileList object is an array-like object, representing a set of selected files, and each member is a File instance. It mainly appeared on two occasions.

-The files property of the file control node (<input type="file">) returns a FileList instance. -When dragging a group of files, the DataTransfer.files property of the target area returns a FileList instance.

// HTML code is as follows
// <input id="fileItem" type="file">
var files = document.getElementById("fileItem").files;
files instanceof FileList; // true

In the above code, the files property of the file control is an instance of FileList.

The instance attribute of FileList is mainly length, which indicates how many files it contains.

The instance method of FileList is mainly item(), which is used to return the instance at the specified position. It accepts an integer as a parameter, which represents the sequence number of the position (starting from zero). However, since the instance of FileList is an array-like object, the square bracket operator can be used directly, that is, myFileList[0] is equivalent to myFileList.item(0), so the item() method is generally not used .

FileReader Object

The FileReader object is used to read the contents of the file contained in the File object or Blob object.

The browser natively provides a FileReader constructor to generate FileReader instances.

var reader = new FileReader();

FileReader has the following instance properties.

-FileReader.error: Error object generated when reading the file -FileReader.readyState: Integer, representing the current state when reading the file. There are three possible states, 0 means no data has been loaded yet, 1 means data is being loaded, and 2 means loading is complete. -FileReader.result: The content of the file after reading is completed. It may be a string or an ArrayBuffer instance. -FileReader.onabort: listener function for abort event (user terminates the reading operation). -FileReader.onerror: listener function for error event (read error). -FileReader.onload: The listener function for the load event (read operation completed), usually the result attribute is used in this function to get the file content. -FileReader.onloadstart: listener function for loadstart event (start of reading operation). -FileReader.onloadend: listener function for loadend event (end of reading operation). -FileReader.onprogress: The listener function for the progress event (reading operation in progress).

The following is an example of listening to the load event.

// HTML code is as follows
// <input type="file" onchange="onChange(event)">

function onChange(event) {
  var file = event.target.files[0];
  var reader = new FileReader();
  reader.onload = function (event) {
    console.log(event.target.result);
  };

  reader.readAsText(file);
}

In the above code, whenever the file control changes, try to read the first file. If the reading is successful (the load event occurs), the content of the file is printed out.

FileReader has the following instance methods.

-FileReader.abort(): Terminate the read operation, the readyState property will become 2. -FileReader.readAsArrayBuffer(): read the file in the format of ArrayBuffer, the result property will return an ArrayBuffer instance after reading. -FileReader.readAsBinaryString(): After reading, the result property will return the original binary string. -FileReader.readAsDataURL(): After reading, the result property will return a string in Data URL format (Base64 encoding), representing the content of the file. For image files, this string can be used in the src attribute of the <img> element. Note that this string cannot be decoded directly by Base64, the prefix data:*/*;base64, must be deleted from the string before decoding. -FileReader.readAsText(): After reading, the result property will return the text string of the file content. The first parameter of this method is the Blob instance representing the file, and the second parameter is optional and represents the text encoding. The default is UTF-8.

Below is an example.

/* HTML code is as follows
  <input type="file" onchange="previewFile()">
  <img src="" height="200">
*/

function previewFile() {
  var preview = document.querySelector("img");
  var file = document.querySelector("input[type=file]").files[0];
  var reader = new FileReader();

  reader.addEventListener(
    "load",
    function () {
      preview.src = reader.result;
    },
    false
  );

  if (file) {
    reader.readAsDataURL(file);
  }
}

In the above code, after the user selects the image file, the script will automatically read the content of the file and assign it as a Data URL to the src attribute of the <img> element to display the image.