SoFunction
Updated on 2025-03-03

ArrayBuffer Uint8Array Blob and text characters conversion example

API introduction

Front-end File upload and download, Canvas save pictures, Ajax and Fetch binary streaming, PDF preview, WebAssembly application on the browser, etc., all require ArrayBuffer and Blob. The file will introduce the mutual conversion of these objects in detail.

FileReaderObjects allow web applications to read asynchronously the content of files (or raw data buffers) stored on the user's computer, usingFileorBlobObject specifies the file or data to be read.

BlobObject represents an immutable, original data-like file object. Its data can be read in text or binary format or converted intoReadableStreamTo be used for data operations.BlobWhat does not necessarily meanJavaScriptData in native format.FileInterface basedBlob, inheritedblobfunction and extend it to support files on the user system.

ArrayBufferObject represents a piece of memory that stores binary data. It cannot be read and written directly, and can only be passed through the view (TypedArrayViews andDataViewViews) are used to read and write. The function of the view is to interpret binary data in a specified format.

Uint8ArrayThe object isArrayBufferA data type (8-bit unsigned integer).

TextEncoderAccept code point streams as input and provideUTF-8Byte stream as output.

TextDecoderThe interface represents a text decoder, and a decoder only supports one specific text encoding, such as utf-8, iso-8859-2, koi8, cp1261, gbk, etc. The decoder takes a stream of bytes as input and provides a stream of code points as output.

Notice:Binary arrays are not real arrays, but array-like objects.

Characters and ArrayBuffer, Uint8Array convert each other

TextEncoder => ArrayBuffer

let encoder = new TextEncoder();

// Characters to Uint8Arraylet uint8Array = ("hello");

// Uint8Array to ArrayBufferlet arrayBuffer = 

Blob => ArrayBuffer

let str = 'hello, how are you?  '
let blob = new Blob([str],{type:'text/plain;charset=utf-8'});
let utf8decoder = new TextDecoder()
().then(buffer=>{
  // ArrayBuffer
  (buffer)
  let text = (buffer)
  // String
  (text)
})

FileReader => ArrayBuffer

let str = 'hello, how are you?  '
let blob = new Blob([str],{type:'text/plain;charset=utf-8'});
let utf8decoder = new TextDecoder()
let fr = new FileReader()
(blob)
 = function(res) {
  // ArrayBuffer
  let buffer = 
  (buffer)
  let text = (buffer)
  // String
  (text)
}

The above is the detailed content of the example of converting ArrayBuffer Uint8Array Blob and text characters. For more information about converting text characters from ArrayBuffer Uint8Array Blob, please follow my other related articles!