This article was first published on my [Personal blog] for more rich front-end learning materials, check out my Github: Leo-javascript covers data structures and algorithms, HTTP, Hybrid, interview questions, React, Angular, TypeScript, Webpack, and more. Click a Star not to get lost ~

Welcome to front-end Zhihu Series:

  • 443- ArrayBuffer and Blob Objects

File objects, FileList objects and FileReader objects are common in File upload and download operations (such as image upload preview, File reading, File upload progress monitoring, etc.).

So this article will introduce both in depth with you.

A File object

1. Concept introduction

The File object provides information about the File and allows JavaScript in the web page to read and write to the File.

The most common use is the file upload control for forms. After the user selects a file on an element, the browser generates an array of each selected file that is a File instance object.

It is also worth mentioning that a File object is a special Blob object and can be used in the context of any Blob object. For example, FileReader, url.createObjecturl (), createImageBitmap(), and xmlHttprequest.send () can all handle blobs and files.

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

2. Object usage

Browsers natively provide a File() constructor that generates File instance objects.

const myFile = new File(bits, name[, options]);
Copy the code

Parameters:

  • bits:

An array representing the contents of a file. Members can be An ArrayBuffer, an ArrayBufferView, a Blob, or an Array of DOMString objects, or any combination of these objects.

ArrayBuffer, ArrayBufferView, and Blob can also be converted to File objects using this parameter.

  • name:

The value is a character string indicating the file name or file path.

  • options:

Configure an object to set the properties of the instance. This parameter is optional. The available values are as follows:

Type: DOMString, which indicates the MIME type of the content to be placed in the file. The default value is “”. LastModified: value representing the Unix timestamp in milliseconds when the file was lastModified. The default is date.now ().

Example:

const myFile = new File(['leo1'.'leo2'].'leo.txt', {type: 'text/plain'});
Copy the code

Create a File object from an existing blob object:

const myFile = new File([blob], 'leo.png', {type: 'image/png'});
Copy the code

3. instance properties and methods

3.1 Instance Attributes

Instances have the following attributes:

  • File.lastModified: Last modified time. read-only

The number of milliseconds since the start of UNIX time (00:00:00 UTC, January 1, 1970)

  • File.name: File name or file path. read-only

For security reasons, the return value does not contain the file path.

  • File.size: File size (in bytes). read-only
  • File.type: MIME type of the file. read-only
// The HTML code is as follows
// <input id="fileItem" type="file">
const myFile = document.getElementById('fileItem')
myFile.addEventListener('change'.function(e){
    const file = this.files[0];
    console.log(file.name);
    console.log(file.size);
    console.log(file.lastModified);
    console.log(file.lastModifiedDate);
});
Copy the code

3.2 Example Method

The File object does not define any methods, but it inherits the following methods from the Blob interface:

  • Blob.slice([start[, end[, contentType]]])

Returns a new Blob object containing data within the specified range in the active Blob object.

4. The compatibility

A FileList object

1. Concept introduction

A FileList object is an array-like object. Each member is an instance of File. It occurs in two cases:

  • through<input type="file">The control offilesProperty, returns oneFileListInstance.

In addition, when the input element has a multiple attribute, you can use it to select multiple files.

  • View by dragging and dropping the fileDataTransfer.filesProperty, returns oneFileListInstance.
// The HTML code is as follows
// <input id="fileItem" type="file">
const files = document.getElementById('fileItem').files;
files instanceof FileList // true

const firstFile = files[0];
Copy the code

2. Object usage

All elements whose type attribute is File have a files attribute that stores the file selected by the user. Such as:

3. instance properties and methods

3.1 Instance Attributes

An instance has only one attribute:

  • FileList.length: Returns the number of files in the list. read-only

3.2 Example Method

An instance has only one method:

  • FileList.item(): is used to return instances at the specified location, starting at 0.

Because a FileList instance is an array like object, you can use the square bracket operator directly, that is, myFileList[0] is equal to myfilelist.item (0), so the item() method is not normally used.

4. The compatibility

Example 5.

Select multiple files and get information for each file:

// The HTML code is as follows
// <input id="myfiles" multiple type="file">
const myFile = document.querySelector("#myfiles");
myFile.addEventListener('change'.function(e){
    let files = this.files;
    let fileLength = files.length;
    let i = 0;
    while ( i < fileLength) {
        let file = files[i];
        console.log(file.name); i++; }});Copy the code

FileReader object

1. Concept introduction

The FileReader object allows a Web application to asynchronously read the contents of a File (or raw data buffer) stored on the user’s computer, using a File or Blob object to specify which File or data to read.

Read the contents of a File or Blob object.

2. Object usage

Browsers natively provide a FileReader constructor that generates instances of FileReader.

const reader = new FileReader();
Copy the code

3. instance properties and methods

FileReader objects have more properties and methods.

3.1 Instance Attributes

  • FileReader.error: indicates an error while reading a file. read-only
  • FileReader.readyState: is an integer that indicates the current status when the file is read. read-only

There are three states: 0: EMPTY, which indicates that no data has been loaded; 1: LOADING: data is being loaded. 2: DONE: the loading is complete.

  • FileReader.resultRead the contents of the file after completion. read-only

Only valid after the read operation is complete, and the data format returned depends on which method was used to initiate the read operation.

3.2 Event Handling

  • FileReader.onabort: handlingabortEvents. The event is in the read operationBe interruptedWhen triggered.
  • FileReader.onerror: handlingerrorEvents. The event is in the read operationAn error occurredWhen triggered.
  • FileReader.onload: handlingloadEvents. The event is in the read operationcompleteWhen triggered.
  • FileReader.onloadstart: handlingloadstarT event. The event is in the read operationstartWhen triggered.
  • FileReader.onloadend: handlingloadendEvents. The event is in the read operationAs the end of theIs triggered (either successfully or failed).
  • FileReader.onprogress: handlingprogressEvents. The event is readingBlobWhen triggered.

3.3 Example Method

  • FileReader.abort(): Terminates the read operation,readyStateThe property will become 2.
  • FileReader.readAsArrayBuffer()To:ArrayBufferFormat to read the file after reading is completeresultProperty will return oneArrayBufferInstance.
  • FileReader.readAsBinaryString(): After reading,resultProperty will beReturns the original binary string.
  • FileReader.readAsDataURL(): After reading,resultProperty returns a string in Data URL format (Base64 encoded) representing the file content.

For image files, this string can be used for the SRC attribute of the element. Note that this string cannot be Base64 decoded directly, and must be prefixed with data:*/*; Base64 is decoded after it is removed from the string.

  • FileReader.readAsText(): After reading,resultProperty returns a text string for the file content.

The first argument to this method is a Blob instance representing the file, and the second argument, optional, represents the text encoding, which defaults to UTF-8.

4. The compatibility

Example 5.

Here’s an example of an image preview:

 

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

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

  if(file) { reader.readAsDataURL(file); }}Copy the code

Iv. Reference materials

  1. File object, FileList object, FileReader object
  2. MDN

Five, about me

This article was first published on pingan8787 personal blog, please keep personal introduction if necessary.

Author Ping-an wang
E-mail [email protected]
Blog posts www.pingan8787.com
WeChat pingan8787
Daily Article recommendations Github.com/pingan8787/…
ES small volumes js.pingan8787.com