New knowledge storeFront end from entry to groundFor attention, star and suggestions, update from time to time ~

You don’t see the total set: from scratch big front-end base building journey (simple, constantly updated ~) ten thousand word long catalogue, feel good, feel free to like it

What is a Blob

Blob (Binary Large Object) represents a Large Object of Binary type. In a database management system, the storage of binary data as a single collection of individuals.

A Blob object represents an immutable, raw data-like file object. Blobs don’t necessarily represent data in JavaScript’s native format. The File interface is based on Blob, inheriting the functionality of Blob and extending it to support files on the user’s system.

Generate a Blob

To construct a BLOb from other non-BLOb objects and data, use the blob () constructor.

The Blob() constructor returns a new Blob object. The content of a BLOB consists of a concatenation of values given in an array of parameters.

Grammar:

var aBlob = new Blob( array, options );
Copy the code

parameter

  • An array is an array made up of objects such as ArrayBuffer, ArrayBufferView, Blob, DOMString, etc., or a mixture of similar objects that will be put into the Blob. DOMStrings will be encoded to UTF-8.
  • Options is an optional BlobPropertyBag dictionary that specifies the following two properties:
    • Type, which defaults to “”, represents the MIME type of the array content to be put into the BLOB.
    • Endings, which specifies how the string containing the line end \n is written. It is one of two values:
      • “Native”, which means that the line terminator is changed to a newline suitable for the host operating system file system, or
      • “Transparent”, the default value, means that the terminator saved in the BLOb is kept unchanged

Construct a BLOB object using a string

var debug = {hello: "world"};
var blob = new Blob([JSON.stringify(debug)], {type : 'application/json'});
Copy the code

The generated BLOB object looks like this:

Blob {
  size: 17
  type: "application/json"
  __proto__: Blob
}
Copy the code

Blob objects have two attributes: size and type. The size attribute is used to represent the size of the data in bytes, and type is a string of MIME type.

Multipurpose Internet Mail Extensions (MIME) Multipurpose Internet Mail Extensions. A type of file with a specified extension that the browser automatically opens when the file is accessed using the specified application. It is used to specify the name of a file customized by the client and the opening mode of some media files.

methods

slice()

The blob.slice () method is used to create a new Blob object containing data in the specified byte range of the source Blob.

grammar

var blob = instanceOfBlob.slice([start [, end [, contentType]]]};
Copy the code

parameter

  • The optional start indicates the starting position of the bytes to be copied into the new Blob. If a negative number is passed in, the offset will be calculated from the end of the data to the front. For example, -10 would be the tenth to last byte of a Blob. The default value is 0, and if you pass a start object larger than the length of the source Blob, you will return a Blob object of 0 length that contains no data.
  • End Optional The byte corresponding to end-1 will be the last byte copied into the new Blob. If a negative number is passed in, the offset will be calculated from the end of the data from back to front. For example, -10 would be the tenth to last byte of a Blob. Its default value is its original length (size).
  • ContentType Optionally gives the new Blob a new document type. This will set its type attribute to the value passed in. Its default value is an empty string.

stream()

Returns a ReadableStream object that, when read, returns the data contained in the Blob.

var stream = blob.stream();
Copy the code

text()

Returns a USVString in UTF-8 format that contains the full contents of the BLOB as a Promise object.

Unicode Scalar Values: A code name for a character.

When returned in JavaScript, USVString maps to String. It is typically only used for performing text processing apis and requires a string of Unicode scalar values to operate.

arrayBuffer()

Returns an ArrayBuffer containing a Promise object in binary format containing all the contents of the BLOB.

FileReader. ReadAsArrayBuffer () this method is similar, but arrayBuffer () returns a promise object, rather than like FileReader returns an event-based API.

Blob usage scenarios

Shard to upload

File objects are special types of BLOBs that can be used in the context of any Blob type.

For large file transfer scenarios, we can use the Slice method to slice large files and then slice them for uploading.

Storing downloaded data

Data downloaded from the Internet can be stored in Blob objects. For example, in some image interfaces that require authentication, we can use fetch, attach authentication information to the request, download the BLOB object, and then use the bloB as a URL using the following method. Or build Blob objects directly on the front end to download front-end files.

axios.get('https://xxxxxx', {responseType: 'blob'}) .then(res => { let url = URL.createObjectURL(res.data) let a = document.createElement('a') A.setattribute ('download', 'picture ') a.href = url a.click()})Copy the code

Blob as a URL

Blob can be done easily,Or the URL of another tag. Blob URL/Object URL is a pseudo-protocol that allows Blob and File objects to be used as URL sources for images, links to download binary data, etc.

In the browser, we create the Blob URL using the url.createObjecturl method, which takes a Blob object and creates a unique URL for it. The lifecycle of this URL and the Document binding in the window that created it. This new URL object represents the specified File object or Blob object. This method creates the memory reference address of an incoming object

It is in the form blob:/, and an example of this is generated in Chrome:

"blob:chrome-extension://lecdifefmmfjnjjinhaennhdlmcaeeeb/0f36aeda-9351-4e38-9379-93efc9360f6b"
Copy the code

The sample

Download the configuration information from the page for easy use.

const config = { name: 'lsqy', password: 'yourpassword', ak: 'XXXXXXXXXX', sk: Const blobContent = new blob ([json.stringify (config, null, 2)], {type: 'application/json'} ); Window. / / build a download link const blobUrl = URL. CreateObjectURL (blobContent) const LNK = document. The createElement method (' a '). The link to download Href = blobUrlCopy the code

When you are done with a URL object, let the browser know that it does not need to keep references to the file in memory by calling url.revokeobjecturl ().

If you get a blobURL and want to re-convert to bloB, you can only re-download the URL as a download link

axios.get('blob:XXX', {responseType: 'blob'})
.then(res => {
    // use res.data
})
Copy the code

Blob converts to Base64

Base64 is a binary data representation method based on 64 printable characters. It is often used to represent, transmit and store binary data in the context of text data processing, including MIME E-mail and SOME complex data of XML.

Most modern browsers support a feature called Data URLs, which allows you to encode the binary Data of an image or other file in Base64 and embed it as a text string in a Web page.

Data URLs are made up of four parts: a prefix (Data:), a MIME type that indicates the Data type, an optional Base64 tag if it’s not text, and the Data itself:

data:[<mediatype>][;base64],<data>
Copy the code

Mediatype is a string of MIME type, such as “image/ JPEG “for A JPEG image file. If omitted, the default is text/plain; Charset = US – ASCII.

If the data is of text type, you can embed the text directly (using the appropriate entity character or escape character, depending on the document type). For binary data, you can base64 encode the data and then embed it. For example, embed an image:

<img alt="logo" src="data:image/png; base64,iVBORw0KGgoAAAANSUhEUg..." >Copy the code

When writing HTML web pages, for some simple images, you usually choose to embed the image content directly in the web page to reduce unnecessary network requests. If you use Webpack, you can enable file-loader and URl-loader. Configure images smaller than a certain size to sneak into a web page using the Data URL.

You can also use Base64 for local preview when uploading images

readBlob(event) { const self = this; const reader = new FileReader(); reader.onload = function () { const base64 = this.result; // img. SRC = base64 self.uploadimage (base64); // Upload base64 data to server}; reader.readAsDataURL(event.target.files[0]); }Copy the code

For FileReader objects, in addition to supporting the conversion of Blob/File objects to Data urls, it also provides readAsArrayBuffer() and readAsText() methods, Used to convert Blob/File objects to other data formats.

The Blob and ArrayBuffer

  • Both BLOBs and ArrayBuffers can store binary data. Blobs store relatively large binary data (such as File File objects).
  • An ArrayBuffer object represents a primitive binary data buffer, that is, a binary buffer (container) of a specified size allocated in memory that is used to store the data of various typed arrays. It is the most basic primitive data container and cannot be read or written directly. Instead, it needs to be read or written through a specific view. That is, a TypedArray object or DataView object reads or writes memory size; A Blob object represents an immutable, raw data-like file object.
  • An ArrayBuffer is stored in memory and can be manipulated directly. Blobs can be on disk, cache memory, and other locations that are not available.
  • They can convert to each other.

Blob => ArrayBuffer

Let blob = new blob ([1,2,3,4]) let reader = new FileReader(); reader.onload = function(result) { console.log(result); } reader.readAsArrayBuffer(blob);Copy the code

ArrayBuffer => Blob

let blob = new Blob([buffer])
Copy the code

Blob with copy and paste

Paste sometimes intercepts images in the input box for uploading. In this case, listen for paste events and get the clipboard files

handlePaste (e) { if (this.paste) { this.uploadFiles(e.clipboardData.files); }}Copy the code

The files we get are files based on blob. You can use all of FileReader’s methods to make a Blib look like you want

Copy Sometimes we need to click a button or right-click menu to trigger a copy event to drop text or images into the clipboard. We also need to generate a BLOB object if it’s a text object

"text/html": new Blob(["<i>Markup</i> <b>text</b>. Paste me into a rich text editor."], { type: "text/html" }),
"text/plain": new Blob(["Fallback markup text. Paste me into a rich text editor."], { type: "text/plain" })
Copy the code

For file type data such as images, you need to fetch the image as a BLOB and throw it to the clipboard

 new ClipboardItem({
      [blob.type]: blob
    })
Copy the code

This article contains: a journey of large front end foundation building from scratch (simple and profound, constantly updated ~)

Recommended reading:

  • Take you rolled a belongs to own the react project | webpack + Babel + typescript + eslint didn’t ridden a project of the couple must not to be missed, take you unlock fast development tips

  • In a few words with you to understand the “closure” | add usage scenario is very simple to explain why going?

  • Reflow and Repaint, KFC and MC are mentioned at the same time every time. The relationship is almost as close as MC beside KFC.

  • Viewport and 1 px | tools: this is a 1 px, designer: no, I can’t, this is not a design but ready to quarrel with me

  • Edible “dry” CSS layout, pure Html example, can debug | horizontal, vertical, multiple columns can watch, adjustable, can be taken away, the only, no branch

  • Front end must master “CSS cascade context” explain | handmade sample, BaoJiao package will sister with cat, what do you want?

Reference documentation

  1. Blob you don’t know
  2. The front-end implements file downloads through Blob
  3. MDN | Blob