ArrayBuffer

An ArrayBuffer object represents a chunk of memory that stores binary data. It cannot be read or written directly and can only be manipulated through views.

// Create a 16-length buffer that allocates a 16-byte contiguous memory space and prefills it with zeros.
const buffer1 = new ArrayBuffer(16);
Copy the code

TypedArray

TypedArray is a set of nine constructors, each of which is a constructor.

The constructor of TypedArray takes three arguments, the first ArrayBuffer object, the byte number at the start of the second view (default: 0), and the byte number at the end of the third view (default: until the end of the memory region).

The name of the Take up the byte describe
Int8Array 1 An 8-bit signed integer
Uint8Array 1 An 8-bit unsigned integer
Uint8ClampedArray 1 Fixed array of 8-bit unsigned integers between 0 and 255
Int16Array 2 16 – bit signed integer
Uint16Array 2 16 – bit unsigned integer
Int32Array 4 32 – bit signed integer
Uint32Array 4 32 – bit unsigned integer
Float32Array 4 32-BIT IEEE floating point number
Float64Array 8 64-BIT IEEE floating point number
// Uint8Array -- Treat each byte in the ArrayBuffer as a single number between 0 and 255 (each byte is 8 bits). This is called an "8-bit unsigned integer".
// Uint16Array -- treat every 2 bytes as an integer between 0 and 65535. This is called a "16-bit unsigned integer".
// Uint32Array -- treat every 4 bytes as an integer between 0 and 4294967295. This is called a "32-bit unsigned integer".
// Float64Array -- Treats every 8 bytes as a float between 5.0x10-324 and 1.8x10308.

const uint8 = new Uint8Array(buffer1);
const uint16 = new Uint16Array(buffer1);
const uint32 = new Uint32Array(buffer1);
const float64 = new Float64Array(buffer1);
Copy the code

DataView

One of the more flexible views is DataView, which supports eight types in addition to the Uint8ClampedArray. DataView is much more convenient than Using TypedArray and requires only one simple creation to perform various transformations.

// Can be converted to various formats
const dataView1 = new DataView(buffer1);
console.log(dataView1);
console.log(dataView1.getUint8(0));
console.log(dataView1.getUint16(0));
console.log(dataView1.getUint32(0));
console.log(dataView1.getFloat64(0));
Copy the code

Blob

A Blob object represents an immutable, raw data-like file object.

// constructor
const blob = new Blob(array, options)
Copy the code
  • Array is an array of objects such as ArrayBuffer, ArrayBufferView, Blob, DOMString, etc. DOMStrings will be encoded as UTF-8.

  • Options is optional and may specify the following two properties:

    • Type. The default value is"", the MIME type of the content.
    • Hamid, the default value is"transparent"To specify the inclusion line terminator\nHow the string is written. It is one of two values:"native", indicating that the end-of-line character is changed to a newline suitable for the host operating system file system, or"transparent", which means that the terminator saved in the BLOB is kept unchanged
const blob1 = new Blob(['hello randy'] and {type: "text/plain" });
Copy the code

Instance properties, methods

attribute

  • typetypeCommon MIME types
  • sizeSize, in bytes
const blob = new Blob(["hello"."randy"] and {type: "text/plain" });
// The output object has the following properties
// size: 10;
// type: "text/plain";
console.log(blob);
Copy the code

methods

  • slice()BlobAnd return a new oneBlobArray, array, arrayslice)
  • arrayBuffer()Returns a binary representation ofpromise
  • stream()Returns aReadableStreamobject
  • text()Returns a textpromise
/ / into the stream
console.log(blob.stream());

/ / to Arraybuffer
blob.arrayBuffer().then((res) = > {
  console.log(res);
});

// Convert to text
blob.text().then((res) = > {
  console.log(res);
});
Copy the code

blob url

A simple way of thinking about it is to convert an object of type file or Blob to a UTF-16 string and store it in memory under the document of the current operation.

The method used to generate the BLOb URL is url.createObjecturl (file/blob). The clearing can only be done by the page unload() event or manually using the URL. RevokeObjectURL (objectURL).

This is often used in front-end downloads.

export const downloadFile = async (params, fileName) => {
  // We use axios to set the interface return type responseType: "blob", so here we return blob from the back end.
  const results = await download(params);
  
  const a = document.createElement("a");
  a.download = fileName + ".xlsx";
  // Generate a BLOb URL. You can use Blob objects or File objects
  a.href = window.URL.createObjectURL(results);
  a.style.display = "none";
  document.body.appendChild(a);
  a.click();
  // Free memory
  window.URL.revokeObjectURL(a.href);
  document.body.removeChild(a);
};
Copy the code

File

File An object that describes information about a File that can be accessed by JavaScript. File inherits from Blob.

const file = new File(array, name[, options])
Copy the code
  • Array is an ArrayBuffer, ArrayBufferView, Blob, DOMString, etc. DOMStrings will be encoded as UTF-8.

  • Name Indicates the file name or file path.

  • Options is optional and may specify the following two properties:

    • Type. The default value is"", the MIME type of the content.
    • LastModified: value representing the Unix timestamp in milliseconds when the file was lastModified. The default is date.now ().

Instance properties, methods

attribute

  • typetypeCommon MIME types
  • sizeSize, in bytes
  • nameThe file name
  • lastModifiedLast modified time (timestamp)
  • lastModifiedDateLast Modified time
const file1 = new File(["File object"]."test", { type: "text/plain" });
// The output object has the following properties
// lastModified: 1640589621358
// lastModifiedDate: Mon Dec 27 2021 15:20:21 GMT+0800 {}
// name: "test"
// size: 12
// type: "text/plain"
// webkitRelativePath: ""
console.log(file1);
Copy the code

methods

  • slice()BlobAnd return a new oneBlobArray, array, arrayslice)
  • arrayBuffer()Returns a binary representation ofpromise
  • stream()Returns aReadableStreamobject
  • text()Returns a textpromise
/ / into the stream
console.log(file1.stream());

/ / to Arraybuffer
file1.arrayBuffer().then((res) = > {
  console.log(res);
});

// Convert to text
file1.text().then((res) = > {
  console.log(res);
});
Copy the code

Base64

define

Base64 is an encoding format that is often encountered in the front end. The format is data:[

][; Base64],
.

In addition to using tools for Base64 encoding, JS also has two built-in methods for string Base64 encoding and decoding.

const str1 = "hello randy";

/ / code
const b1 = window.btoa(str1);
console.log(b1); // aGVsbG8gcmFuZHk=

/ / decoding
const str2 = window.atob(b1);
console.log(str2); // hello randy
Copy the code

Turn the Blob Base64

const blob = new Blob(["hello"."randy"] and {type: "text/plain" });
const fileReader = new FileReader();
fileReader.readAsDataURL(blob);
fileReader.onload = () = > {
  console.log(fileReader.result); // "data:text/plain; base64,aGVsbG9yYW5keQ=="
};
Copy the code

advantages

  1. You can convert binary data (such as images) into printable characters for easy data transfer.
  2. Simple encryption of data is safe to the naked eye.
  3. If you are processing images in HTML or CSS, you can reduce HTTP requests.

disadvantages

  1. Content becomes larger after encoding, at least 1/3 larger. Because three bytes become four bytes, when there is only one byte, there will be at least three bytes.
  2. Encoding and decoding requires additional work.

FileReader

FileReader objects allow Web applications to asynchronously read the contents of files (or raw data buffers) stored on the user’s computer.

attribute

attribute describe
FileReader.error A DOMException, indicating an error occurred while reading the file.
FileReader.result Returns the contents of the file. This property is valid only after the read operation is complete, and the format of the data returned depends on which read method was used to perform the read operation.
FileReader.readyState A number representing the FileReader status. 0 has not loaded any data yet. 1 Data is being loaded. 2 All read requests have been completed.

methods

Note that whether the read succeeds or fails, the method does not return the read result, which is stored in the Result property.

The method name describe
FileReader.abort() Abort the read operation. On return, the readyState property is DONE.
FileReader.readAsArrayBuffer() Convert the read content into an ArrayBuffer.
FileReader.readAsBinaryString() Convert what is read into binary data.
FileReader.readAsDataURL() Converts what is read into and encodes it as base64’s Data URL. Format isdata:[<mediatype>][;base64],<data>
FileReader.readAsText() Reads the data as a text string in the given encoding (utF-8 encoding by default).

The event

The event describe
FileReader.onabort Handle abort events. This event is emitted when the read operation is interrupted.
FileReader.onerror Handle error events. This event is emitted when an error occurs in a read operation.
FileReader.onload Handle the Load event. This event is emitted when the read operation is complete.
FileReader.onloadstart Handles the LoadStart event. This event is emitted when the read operation begins.
FileReader.onloadend Handles the LoadEnd event. This event is emitted at the end of a read operation (either successful or failed).
FileReader.onprogress Process the Progress event. This event is triggered when a Blob is read.

example

const blob3 = new Blob(["hello"."randy"] and {type: "text/plain" });

const fileReader = new FileReader();

fileReader.readAsDataURL(blob3);

fileReader.onload = () = > {
  console.log(fileReader);
  // Get the result by fileReader
  // filereader. result is the result (if successful)
  // filereader. error is error (if failed).
};
Copy the code

transformation

Blob and File conversions

Turn a Blob File

const blob1 = new Blob(["Blob files"] and {type: "text/plain" });
/ / blob file
const file2 = new File([blob1], "test2", { type: blob1.type });
console.log("file2: ", file2);
Copy the code

The File transfer Blob

const file1 = new File(["File object"]."test", { type: "text/plain" });
/ / file blob
const blob2 = new Blob([file1], { type: file1.type });
console.log("blob2: ", blob2);
Copy the code

Change File, Blob, and img to Base64

Turn the Blob Base64

/ / Blob Base64
const blob = new Blob(["hello"."randy"] and {type: "text/plain" });

const fileReader = new FileReader();

fileReader.readAsDataURL(blob);

fileReader.onload = () = > {
  console.log(fileReader.result); // "data:text/plain; base64,aGVsbG9yYW5keQ=="
};
Copy the code

The File transfer Base64

/ / File Base64
const file1 = new File(["File object"]."test", { type: "text/plain" });

const fileReader = new FileReader();

fileReader.readAsDataURL(file1);

fileReader.onload = () = > {
  console.log(fileReader); // "data:text/plain; Base64, 5 pah5lu25a + 56 LGH. ""
};
Copy the code

Img turn Base64

// Local image to base64, note that the link is local link, not network address.
const img2base64 = (imgUrl) = > {
  let image = new Image();
  image.src = imgUrl;
  return new Promise((resolve) = > {
    image.onload = () = > {
      let canvas = document.createElement("canvas");
      canvas.width = image.width;
      canvas.height = image.height;
      var context = canvas.getContext("2d");
      context.drawImage(image, 0.0, image.width, image.height);
      let dataUrl = canvas.toDataURL("image/png");
      resolve(dataUrl);
    };
  });
};

img2base64(".. /vue2/src/assets/logo.png").then((res) = > {
  console.log(res);
});
Copy the code

Base64 to Blob and File

Turn Base64 Blob

function dataURLtoBlob(dataurl) {
  // `data:[<mediatype>][;base64],<data>`
  var arr = dataurl.split(","),
    mime = arr[0].match(/ : (. *?) ; /) [1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}
Copy the code

Base64 transfer the File

function dataURLtoFile(dataurl, filename) {
  // Convert base64 to a file
  var arr = dataurl.split(","),
    mime = arr[0].match(/ : (. *?) ; /) [1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: mime });
}
Copy the code

Refer to the article

JavaScript FileReader object details

The differences between Blob, ArrayBuffer, File, FileReader and FormData

Blob, ArrayBuffer, File, FileRender, FormData

Afterword.

This article is the author’s personal study notes, if there are fallacies, please inform, thank you! If this article helped you, please give it a thumbs up